snippetpythonModeratepending
Python pathlib -- modern file path handling
Viewed 0 times
pathlibPathfile handlingglobresolvecross-platform
python
Problem
String concatenation for file paths is fragile, OS-dependent, and error-prone. os.path.join works but is verbose.
Solution
Use pathlib.Path for object-oriented file system operations. Supports / operator for joining, glob patterns, and cross-platform paths.
Code Snippets
pathlib essentials
from pathlib import Path
# Join paths with /
config = Path.home() / '.config' / 'myapp' / 'settings.json'
# Read/write
data = config.read_text()
config.write_text(json.dumps(settings))
# Create directories
config.parent.mkdir(parents=True, exist_ok=True)
# Glob
for py_file in Path('src').rglob('*.py'):
print(py_file.stem) # filename without extension
# Properties
p = Path('/home/user/docs/report.tar.gz')
p.name # 'report.tar.gz'
p.stem # 'report.tar'
p.suffix # '.gz'
p.suffixes # ['.tar', '.gz']
p.parent # Path('/home/user/docs')
p.is_file() # True/False
p.resolve() # absolute pathRevisions (0)
No revisions yet.