snippetpythonModeratepending
Python pathlib patterns — modern file system operations
Viewed 0 times
pathlibPathos.path replacementfile operationsglobread_text
terminallinuxmacos
Problem
Still using os.path.join(), os.path.exists(), and open() for file operations. The os.path API is stringly-typed and verbose. Need a cleaner, object-oriented approach to file system operations.
Solution
pathlib provides an OOP interface for file paths. Replaces most os.path, glob, and open() usage. Works cross-platform.
Code Snippets
pathlib replacing os.path for all file operations
from pathlib import Path
# Construction
root = Path('/Users/me/project')
config = root / 'config' / 'settings.json' # / operator joins
# Reading and writing
text = config.read_text(encoding='utf-8')
config.write_text('{"key": "value"}', encoding='utf-8')
bytes_data = Path('image.png').read_bytes()
# Properties
print(config.name) # 'settings.json'
print(config.stem) # 'settings'
print(config.suffix) # '.json'
print(config.parent) # Path('/Users/me/project/config')
print(config.exists()) # True/False
print(config.is_file()) # True/False
# Globbing
for py_file in root.rglob('*.py'): # recursive
print(py_file.relative_to(root))
for md_file in root.glob('docs/*.md'): # non-recursive
print(md_file)
# Directory operations
(root / 'output').mkdir(parents=True, exist_ok=True)
# Current file's directory (replaces os.path.dirname(__file__))
here = Path(__file__).resolve().parent
data_file = here / 'data' / 'input.csv'
# Iteration
for item in root.iterdir():
if item.is_dir():
print(f'Directory: {item.name}')Revisions (0)
No revisions yet.