os.makedirs creates a directory together with any intermediate directories required by its path. Unlike os.mkdir, it can build the missing directory structure in one call. section 12.4
Use it when a filesystem operation needs a destination directory:
- Call os.makedirs('mydir') to create a directory, then verify it with os.path.isdir('mydir'). section 12.4
- Pass exist_ok=True when the directory may already exist, as in os.makedirs(new_path, exist_ok=True). section 12.6.2
- Use os.mkdir when intermediate directories are not needed; choose os.makedirs for nested paths or setup code. section 12.4
Create a backup directory before moving files
import os new_path = os.path.join('.', 'backup') os.makedirs(new_path, exist_ok=True) # Later, matching files can be moved into new_path with os.rename(...). section 12.6.2
os.makedirs('mydir')
os.listdir(os.curdir)
['anscombe.json',
'README.md.old',
'mydir',
'1.tmp',
'2.tmp',
'california_housing_train.csv',
'california_housing_test.csv',
'mnist_test.csv',
'mnist_train_small.csv']
os.path.isdir('mydir')
True
Inspect a compact session that creates mydir, lists the working directory, and confirms the result with os.path.isdir. section 12.4
