pathlib – Make sure directory path exists

We can use pathlib to make sure a path exists and to create it if it doesn’t.

Snippet

1
2
3
4
5
6
7
8
from pathlib import Path


# Create a Path object with the path we want to use.
mypath = Path("images", "thumbnail")

# Create the path
mypath.mkdir(parents=True, exist_ok=True)

Code with details

from pathlib import Path


# Create a Path object with the path we want to use.
mypath = Path("images", "thumbnail")

# Use the .exists() method to see if the path exists or not.
# The path (images/thumbnail) doesn't exist yet.
print(mypath.exists())
>> False

"""
Create the path. 
parents=True means create the whole path. So in our example, 
if "images" does not exist, it will create it, because it's the parent of "thumbnail". 
It will also create "thumbnail"

---parents argument:
if we use parents=False, the call below will expect "images" to already exist. It will still create the "thumbnail" folder if it doesn't exist, but it won't create the parent folder, "images".
If the parent folder, "images", doesn't exist, it will raise an exception if parents=False.
"""

---exist_ok argument:
exist_ok=True means don't raise an exception if the path already exists.
mypath.mkdir(parents=True, exist_ok=True)

print(mypath.exists())
>> True