patternpythonnoneTip
pathlib vs os.path: Modern File Path Handling
Viewed 0 times
Python 3.4+
pathlibPathos.pathfile systemglobmkdircross-platform
Problem
Code using os.path for file operations is verbose, requires manual string concatenation, and is hard to read. Path manipulation with string operations is error-prone on Windows.
Solution
Use pathlib.Path for all file system operations — it is object-oriented, readable, and cross-platform.
from pathlib import Path
# Creating paths — / operator joins parts cleanly
base = Path('/data')
config = base / 'config' / 'settings.json'
# Reading and writing — no open() needed for simple cases
content = config.read_text(encoding='utf-8')
config.write_text('{}', encoding='utf-8')
# File info
config.exists()
config.is_file()
config.stat().st_size
# Parts and transformations
path = Path('/data/reports/report.csv.gz')
path.name # 'report.csv.gz'
path.stem # 'report.csv'
path.suffix # '.gz'
path.parent # Path('/data/reports')
# Globbing
for csv_file in Path('data').glob('**/*.csv'):
print(csv_file)
# Creating directories
Path('/data/new/dir').mkdir(parents=True, exist_ok=True)Why
pathlib.Path is object-oriented, cross-platform, and chainable. It replaces os.path, os.getcwd(), os.makedirs(), and file open patterns with a unified, readable API.
Gotchas
- Some older libraries still require str(path) rather than accepting Path objects directly.
- Path('~').expanduser() is needed for home directory paths — Path('~') is a literal path.
- Path is immutable — all operations return new Path objects.
Revisions (0)
No revisions yet.