Python pathlib make directories if they don’t exist

Jasonca1 picture Jasonca1 · May 1, 2018 · Viewed 37.2k times · Source

If I wanted to specify a path to save files to and make directories that don’t exist in that path, is it possibly to do this using the pathlib library in one line of code?

Answer

wim picture wim · May 1, 2018

Yes, that is Path.mkdir:

pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)

From the docs:

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raises FileNotFoundError.

If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.