Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pathlib make directories if they don’t exist

Tags:

python

pathlib

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

like image 407
Jasonca1 Avatar asked Sep 25 '22 17:09

Jasonca1


People also ask

How do you create a directory if it doesn't exist in Python?

To create a directory if not exist in Python, check if it already exists using the os. path. exists() method, and then you can create it using the os. makedirs() method.

How do I create a folder using Pathlib?

Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .

How do I create a nested directory in Python?

For python 3.2 and above, you can use os. makedirs . Using method makedirs() from module os , a nested directory can be created in a simple way. The parameter passed is the nested directory we wanted to create.

Is Pathlib better than os?

In this article, I have introduced another Python built-in library, the Pathlib. It is considered to be more advanced, convenient and provides more stunning features than the OS library. Of course, we still need to know how to use the OS library as it is one of the most powerful and basic libraries in Python.


2 Answers

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.

like image 274
wim Avatar answered Oct 07 '22 03:10

wim


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")
like image 9
Kolibril Avatar answered Oct 07 '22 03:10

Kolibril