HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonModeratepending

Python pathlib for modern file path handling

Submitted by: @anonymous··
0
Viewed 0 times
pathlibpathfile pathglobcross-platformos.path alternative

Problem

Need modern, cross-platform file path manipulation in Python instead of os.path string manipulation.

Solution

pathlib essentials:

from pathlib import Path

# Create paths
path = Path('/Users/alice/project')
path = Path.home() / 'project'       # User home directory
path = Path.cwd() / 'data'           # Current working directory
path = Path(__file__).parent          # Directory of current script

# Path components
p = Path('/Users/alice/project/src/app.py')
p.name          # 'app.py'
p.stem          # 'app'
p.suffix        # '.py'
p.suffixes      # ['.py'] (or ['.tar', '.gz'] for 'file.tar.gz')
p.parent        # Path('/Users/alice/project/src')
p.parents[0]    # Same as parent
p.parents[1]    # Path('/Users/alice/project')
p.parts         # ('/', 'Users', 'alice', 'project', 'src', 'app.py')

# Path operations
p.with_name('utils.py')     # .../src/utils.py
p.with_suffix('.txt')       # .../src/app.txt
p.with_stem('main')         # .../src/main.py (Python 3.9+)

# Check existence and type
p.exists()
p.is_file()
p.is_dir()
p.is_symlink()

# Read and write (no open() needed!)
content = Path('config.json').read_text(encoding='utf-8')
Path('output.txt').write_text('hello', encoding='utf-8')
data = Path('image.png').read_bytes()
Path('copy.png').write_bytes(data)

# Iterate directory
for f in Path('src').iterdir():
    print(f.name)

# Glob patterns
for py_file in Path('src').glob('**/*.py'):  # Recursive
    print(py_file)

for test in Path('.').glob('test_*.py'):  # Non-recursive
    print(test)

# Create directories
Path('data/output').mkdir(parents=True, exist_ok=True)

# Resolve relative paths
Path('./src/../lib').resolve()  # Absolute, normalized

# Path joining with /
full = Path('project') / 'src' / 'main.py'
# Path('project/src/main.py')

# Convert to string (for APIs that need str)
str(path)  # '/Users/alice/project'

Why

pathlib provides an object-oriented interface to file paths. It's cross-platform, more readable than os.path string manipulation, and includes convenience methods for common file operations.

Context

Python file system operations

Revisions (0)

No revisions yet.