To check if a directory exists in Python, you can use either the os
module or the pathlib
module (Python 3.4+). Here’s how to do it:
Method 1: Using os.path.isdir
import os
directory_path = "/path/to/directory"
if os.path.isdir(directory_path):
print(f"The directory '{directory_path}' exists.")
else:
print(f"The directory '{directory_path}' does not exist.")
Key Notes:
- Behavior: Returns
True
if the path exists and is a directory. - Handles: Symbolic links (returns
True
if the link points to a directory). - Case Sensitivity: Matches the OS (case-sensitive on Linux/macOS, case-insensitive on Windows).
Method 2: Using pathlib
(Modern/OOP Approach)
from pathlib import Path
directory_path = Path("/path/to/directory")
if directory_path.is_dir():
print(f"The directory '{directory_path}' exists.")
else:
print(f"The directory '{directory_path}' does not exist.")
Key Notes:
- Object-Oriented: Uses
Path
objects for cleaner code. - Same Behavior: Like
os.path.isdir
, it checks both existence and directory type.
Edge Cases
- Check if a Path Exists (File or Directory):
os.path.exists("/path/to/item") # True if file/directory exists
- Check if a Path is a File:
os.path.isfile("/path/to/file") # True if path is a file
- Symbolic Links:
os.path.isdir
andPath.is_dir()
follow symbolic links by default.- To check if a path is a symbolic link itself (not its target), use:
python os.path.islink("/path/to/symlink") # True if path is a symlink
Example Workflow
from pathlib import Path
def check_directory(path):
dir_path = Path(path)
if dir_path.is_dir():
print(f"Directory '{dir_path}' exists.")
else:
print(f"Directory '{dir_path}' does not exist. Creating it...")
dir_path.mkdir(parents=True, exist_ok=True) # Optional: Create the directory
check_directory("./my_folder")
Summary
- Use
os.path.isdir
for quick checks (traditional approach). - Use
pathlib.Path.is_dir()
for modern, readable code. - Both methods reliably check for directory existence across OS platforms.