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?
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.
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 .
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.
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.
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 POSIXmkdir -p
command), but only if the last path component 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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With