liveBook · Manning

Path.mkdir

As explained in The Quick Python Book, Fourth Edition

Path.mkdir is a pathlib method that creates the directory represented by a path, optionally creating missing parent directories.

Path.mkdir creates the directory represented by a pathlib Path object. Without parent creation enabled, an absent intermediate directory causes FileNotFoundError; with parents=True, pathlib creates the necessary directory chain. section 12.4.1

Use the method through a Path object:

  • Create a directory with Path('mydir').mkdir(). section 12.4.1
  • Pass parents=True when one or more required intermediate directories do not yet exist. section 12.4.1
  • Pass exist_ok=True when creating a directory that may already exist, as in a reusable backup-directory setup. section 12.6.2

Create and verify a directory

from pathlib import Path new_path = Path('mydir') new_path.mkdir(parents=True) print(new_path.is_dir()) # True new_path.rmdir()

Prepare a backup directory

from pathlib import Path backup_dir = Path('backup') backup_dir.mkdir(exist_ok=True) for file in Path('.').rglob('*.test'): if not file.is_symlink(): file.rename(backup_dir / file.name)

new_path = Path ('mydir')
new_path.mkdir(parents=True)
list(cur_path.iterdir())
 
[PosixPath('anscombe.json'),
 PosixPath('README.md'),
 PosixPath('.ipynb_checkpoints'),
 PosixPath('mydir'),
 PosixPath('2.tmp'),
 PosixPath('california_housing_train.csv'),
 PosixPath('california_housing_test.csv'),
 PosixPath('mnist_test.csv'),
 PosixPath('mnist_train_small.csv')]
 
new_path.is_dir()
 
True

Inspect the complete directory-creation example and its resulting directory listing. section 12.4.1

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains basic creation, parent-directory handling, existing-directory tolerance, and the related removal operation.
Examples
Demonstrates creating mydir, checking it with is_dir(), removing it, and preparing a backup directory for .test files.
What it assumes
Assumes familiarity with Python and pathlib Path objects while demonstrating directory creation from concrete examples.
What you can do after
Operate/configure pathlib directory creation with parents and exist_ok while preparing filesystem workflows.
How it connects
Connects pathlib Path objects with filesystem traversal, file moves, directory removal, and the os.makedirs alternative.

Related concepts

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.