liveBook · Manning

Os.makedirs

As explained in The Quick Python Book, Fourth Edition

os.makedirs is an os-module function that creates a directory and any required intermediate directories.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines the function, contrasts it with os.mkdir, and demonstrates exist_ok in a file-processing workflow.
Examples
Uses mydir for a basic creation check and backup for a directory supporting recursive file processing and moves.
What it assumes
Assumes familiarity with path strings, the os module, and basic filesystem operations.
What you can do after
Operate filesystem workflows by creating required directories and safely preparing an existing-directory destination with exist_ok=True.
How it connects
Connects directory creation with os.mkdir, os.path, os.walk, os.rename, and pathlib.

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.