pathlib module provides classes for working with filesystem paths in an object-oriented way. It’s the modern replacement for many os.path operations.
Module Import
Creating Path Objects
Path() - Platform-Specific Path
Path Operators
Use/ operator to join paths:
Path Properties
Path Components
Path Types
File Operations
Reading Files
Writing Files
File Information
Directory Operations
Listing Contents
Creating and Removing Directories
Path Manipulation
Joining Paths
Changing Path Components
Resolving Paths
File Operations
Renaming and Moving
Copying Files
Permissions
Special Methods
Path Matching
Symbolic Links
Practical Examples
Find All Files with Extension
Calculate Directory Size
Backup Files with Timestamp
Clean Up Old Files
Process All Files in Directory
Path Types
Pure Paths (No I/O)
Concrete Paths (With I/O)
Best Practices
Always use parents=True when creating nested directories:
Migration from os.path
| os.path | pathlib |
|---|---|
os.path.join(a, b) | Path(a) / b |
os.path.exists(path) | Path(path).exists() |
os.path.isfile(path) | Path(path).is_file() |
os.path.isdir(path) | Path(path).is_dir() |
os.path.basename(path) | Path(path).name |
os.path.dirname(path) | Path(path).parent |
os.path.splitext(path) | Path(path).stem, Path(path).suffix |
os.path.abspath(path) | Path(path).resolve() |
os.getcwd() | Path.cwd() |
os.path.expanduser('~') | Path.home() |
Related Modules
os
Operating system interfaces
shutil
High-level file operations
glob
Unix-style pathname patterns
tempfile
Temporary files
