snippetpythonTippending
Python pathlib recipes for common file operations
Viewed 0 times
pathlibPathfiledirectoryglobread_text
Problem
Using os.path for file operations is verbose and string-based. Need cleaner file path manipulation.
Solution
pathlib provides an object-oriented interface for paths:
from pathlib import Path
# Construction
p = Path('/usr/local/bin')
p = Path.home() / '.config' / 'app' # operator / for joining
p = Path.cwd() / 'data'
# Reading and writing
content = Path('config.json').read_text(encoding='utf-8')
Path('output.txt').write_text('hello', encoding='utf-8')
data = Path('image.png').read_bytes()
# Inspection
p.exists() # True/False
p.is_file() # True if regular file
p.is_dir() # True if directory
p.name # 'file.tar.gz'
p.stem # 'file.tar'
p.suffix # '.gz'
p.suffixes # ['.tar', '.gz']
p.parent # parent directory
p.parts # ('/', 'usr', 'local', 'bin')
# Searching
list(Path('.').glob('*.py')) # Python files in cwd
list(Path('.').rglob('*.py')) # Recursive
list(Path('.').glob('**/*.test.ts')) # Test files recursive
# Modification
p.with_suffix('.json') # change extension
p.with_name('other.py') # change filename
p.resolve() # absolute path
# Directory ops
Path('a/b/c').mkdir(parents=True, exist_ok=True)
for child in Path('.').iterdir(): print(child)
from pathlib import Path
# Construction
p = Path('/usr/local/bin')
p = Path.home() / '.config' / 'app' # operator / for joining
p = Path.cwd() / 'data'
# Reading and writing
content = Path('config.json').read_text(encoding='utf-8')
Path('output.txt').write_text('hello', encoding='utf-8')
data = Path('image.png').read_bytes()
# Inspection
p.exists() # True/False
p.is_file() # True if regular file
p.is_dir() # True if directory
p.name # 'file.tar.gz'
p.stem # 'file.tar'
p.suffix # '.gz'
p.suffixes # ['.tar', '.gz']
p.parent # parent directory
p.parts # ('/', 'usr', 'local', 'bin')
# Searching
list(Path('.').glob('*.py')) # Python files in cwd
list(Path('.').rglob('*.py')) # Recursive
list(Path('.').glob('**/*.test.ts')) # Test files recursive
# Modification
p.with_suffix('.json') # change extension
p.with_name('other.py') # change filename
p.resolve() # absolute path
# Directory ops
Path('a/b/c').mkdir(parents=True, exist_ok=True)
for child in Path('.').iterdir(): print(child)
Why
pathlib replaces os.path with a cleaner API. It's the recommended way to handle paths in modern Python (3.4+).
Revisions (0)
No revisions yet.