Expert guidance on using Python's pathlib module for object-oriented filesystem path manipulation
Expert guidance on Python's `pathlib` module for object-oriented filesystem path operations based on official Python 3.14 documentation.
Provides comprehensive knowledge of Python's pathlib module for modern, object-oriented filesystem path manipulation. Helps developers choose between pure paths (computational only) and concrete paths (with I/O), understand cross-platform path handling, and use pathlib effectively for file operations.
When the user asks about Python filesystem paths, pathlib usage, or file operations:
1. **Assess the use case:**
- Determine if the task requires I/O operations (use `Path`) or pure path manipulation (use `PurePath`)
- Check if cross-platform path handling is needed (e.g., Windows paths on Unix)
- Identify whether the user needs read/write operations, path queries, or pattern matching
2. **Recommend the appropriate class:**
- **`Path`** - Default choice for most filesystem tasks (auto-detects platform)
- **`PurePath`** - For path manipulation without filesystem access
- **`PurePosixPath`** / **`PureWindowsPath`** - For platform-specific pure paths
- **`PosixPath`** / **`WindowsPath`** - For platform-specific concrete paths
3. **Provide code examples for common operations:**
**Basic path creation and navigation:**
```python
from pathlib import Path
# Create path object
p = Path('.')
# Join paths with / operator
config = p / 'config' / 'settings.json'
# List directory contents
subdirs = [x for x in p.iterdir() if x.is_dir()]
# Find files with glob patterns
python_files = list(p.glob('**/*.py'))
```
**Path properties and queries:**
```python
p = Path('/etc/init.d/reboot')
# Check existence and type
p.exists() # True/False
p.is_dir() # True/False
p.is_file() # True/False
# Resolve symlinks and relative paths
resolved = p.resolve()
# Access path components
p.parts # Tuple of path segments
p.parent # Parent directory
p.name # Final component
p.stem # Filename without extension
p.suffix # File extension
```
**File operations:**
```python
# Read file
with p.open() as f:
content = f.read()
# Or use convenience methods
text = p.read_text()
data = p.read_bytes()
# Write file
p.write_text('content')
p.write_bytes(b'binary data')
```
4. **Handle platform differences:**
- Explain that `Path()` automatically instantiates the correct platform-specific class
- Note Windows-specific features: drives (`c:`), UNC paths (`//server/share`)
- Mention that forward slashes work on Windows for path construction
- Use pure path classes when manipulating paths for a different OS
5. **Common patterns:**
- Use `/` operator for joining paths instead of string concatenation
- Prefer `path.read_text()` / `path.write_text()` for simple file I/O
- Use `glob()` or `rglob()` for pattern matching instead of `os.walk()`
- Access path components via properties (`.name`, `.stem`, `.suffix`) instead of string operations
- Use `.resolve()` to canonicalize paths and resolve symlinks
6. **Address gotchas:**
- Absolute path segments reset the path (like `os.path.join()`)
- Double dots (`..`) are NOT collapsed automatically (use `.resolve()`)
- `bytes(path)` only recommended on Unix
- Empty pathsegments defaults to current directory (`.`)
7. **Provide alternatives when appropriate:**
- Mention `os.path` for low-level string manipulation
- Reference `os.fspath()` for converting path objects to strings
- Note that pathlib objects implement `os.PathLike` interface
**Path creation:** `Path()`, `PurePath()`, `PurePosixPath()`, `PureWindowsPath()`
**Properties:** `.parts`, `.drive`, `.root`, `.anchor`, `.parents`, `.parent`, `.name`, `.stem`, `.suffix`, `.suffixes`
**Path operations:** `/` (join), `.joinpath()`, `.resolve()`, `.absolute()`, `.relative_to()`, `.with_name()`, `.with_stem()`, `.with_suffix()`
**Queries:** `.exists()`, `.is_dir()`, `.is_file()`, `.is_symlink()`, `.is_absolute()`
**I/O operations:** `.open()`, `.read_text()`, `.read_bytes()`, `.write_text()`, `.write_bytes()`
**Directory operations:** `.iterdir()`, `.glob()`, `.rglob()`, `.mkdir()`, `.rmdir()`
**File operations:** `.touch()`, `.unlink()`, `.rename()`, `.replace()`, `.chmod()`
**User:** "How do I find all JSON files in a directory recursively?"
**Assistant:**
```python
from pathlib import Path
json_files = Path('.').rglob('*.json')
json_files = Path('.').glob('**/*.json')
for json_file in json_files:
print(json_file)
# Process file...
```
**User:** "How do I get the filename without extension?"
**Assistant:**
```python
from pathlib import Path
p = Path('/data/report.csv')
print(p.stem) # Output: 'report'
print(p.name) # Output: 'report.csv'
print(p.suffix) # Output: '.csv'
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/python-pathlib-reference/raw