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
