How to Check If a Directory Exists in Python
Created
Modified
Using os.path.isdir Method
You can use os.path.isdir()
to check if a directory exists, it really simple. For example,
#!/usr/bin/python3
# Import module
import os
d = "./folder"
print(os.path.isdir(d))
True
Using os.path.exists Method
The os.path.exists()
method returns True if path refers to an existing path or an open file descriptor.
For both files and directories:
#!/usr/bin/python3
# Import module
import os
f = "./folder/file.txt"
print(os.path.exists(f))
d = "./folder"
print(os.path.exists(d))
True True
Using pathlib Module
You can use pathlib:
#!/usr/bin/python3
# Import module
import pathlib
d = "./folder"
print(pathlib.Path(d).is_dir())
True