makedirs to create deep hierarchical directories recursively in Python

Money and Business

Error when creating a new directory with os.mkdir() in a non-existent directory

os.mkdir()This is the method used to create a directory (folder) in Python. If you try to create a new directory in a non-existent directory, an error will occur.(FileNotFoundError)

import os

os.mkdir('not_exist_dir/new_dir')
# FileNotFoundError

Create directories recursively with os.madeirs()

If you use os.makedirs() instead of os.mkdir(), it will create an intermediate directory, so you can recursively create a deep hierarchical directory.

os.makedirs('not_exist_dir/new_dir')

In the case of this example, it will create all of them at once. It is OK if there are multiple new intermediate directories.

  • intermediate directory: not_exist_dir
  • final directory: new_dir

However, if the end directory already exists, an error will occur.(FileExistsError)

os.makedirs('exist_dir/exist_dir')
# FileExistsError

If there is an argument exist_ok

Since Python 3.2, the argument exist_ok has been added, and if exist_ok=True, no error will occur even if the end directory already exists. If the end directory does not exist, a new one will be created, and if it does exist, nothing will be done. This is convenient because you don't need to check the existence of the terminal directory in advance.

os.makedirs('exist_dir/exist_dir', exist_ok=True)

If the argument exist_ok is missing

If you have an older version of Python and do not have the argument exist_ok in os.madeirs, you can use os.path.exists to determine whether or not there is an end directory, and then create a new one only if there is no end directory.

if not os.path.exists('exist_dir/exist_dir'):
    os.makedirs('exist_dir/exist_dir')
Copied title and URL