Python pathlib make directories if they don’t exist Python pathlib make directories if they don’t exist python python

Python pathlib make directories if they don’t exist


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 asneeded; they are created with the default permissions without takingmode into account (mimicking the POSIX mkdir -p command).

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

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

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


This gives additional control for the case that the path is already there:

path = Path.cwd() / 'new' / 'hi' / 'there'try:    path.mkdir(parents=True, exist_ok=False)except FileExistsError:    print("Folder is already there")else:    print("Folder was created")