The Python pathlib module provides an object-oriented, cross-platform framework for handling filesystem paths, replacing older string-based modules like os.path. Instead of manipulating raw strings, you work directly with Path objects that automatically handle variations between operating systems (like / vs. )
Creating and Joining Paths
- You can create a Path object by passing a string, using environment-based methods, or combining them with the / operator
from pathlib import Path
# Create a path from a string
path1 = Path("documents") / "reports" / "data.csv"
# Get important system directories
cwd = Path.cwd() # Current working directory
home = Path.home() # User's home directory
# Convert relative path to absolute
absolute_path = path1.resolve()
Extracting Path Components
- If you have a path like /home/user/documents/report.tar.gz, pathlib makes it incredibly easy to extract individual components using properties
File and Directory Operations
- You no longer need to import separate modules to create, delete, or check files.
path = Path("data/records.txt")
# Check status and types
print(path.exists()) # True if path exists
print(path.is_file()) # True if it's a file
print(path.is_dir()) # True if it's a directory
# Creating items
path.parent.mkdir(parents=True, exist_ok=True) # Safely make directories
path.touch() # Create empty file
# Deleting items
path.unlink() # Delete a file
path.parent.rmdir() # Delete an EMPTY directory
Searching & Directory Iteration
You can easily navigate through folders or search for specific file patterns using glob and rglob (recursive glob)
dir_path = Path("my_project")
# Iterate over immediate contents
for item in dir_path.iterdir():
print(item.name)
# Find all .py files in this folder
py_files = dir_path.glob("*.py")
# Find all .csv files here AND in all subfolders recursively
all_csv_files = dir_path.rglob("*.csv")

Top comments (0)