How to Parse Path Components with pathlib Path in Python
Parse a file path into parent directory, filename, stem, suffix, and parts using the standard library pathlib module.
Python code
12 linesfrom pathlib import Path
if __name__ == "__main__":
p = Path("data/reports/2024/final.txt")
print(f"Path: {p}")
print(f"Parent: {p.parent}")
print(f"Name: {p.name}")
print(f"Stem: {p.stem}")
print(f"Suffix: {p.suffix}")
print(f"Parts: {p.parts}")
print(f"Anchor: {p.anchor}")
print(f"Drive: {p.drive}")
Output
Path: data/reports/2024/final.txt
Parent: data/reports/2024
Name: final.txt
Stem: final
Suffix: .txt
Parts: ('data', 'reports', '2024', 'final.txt')
Anchor:
Drive:
How it works
The Path object from the standard library parses a path string into a structured object. Accessing p.parent returns the path's parent directory as a Path, p.name gives the final component, and p.stem splits off the suffix. The p.suffix property returns the file extension including the dot, while p.parts is a tuple of all components. On POSIX systems, anchor and drive are empty strings, making them important for cross-platform code.
Common mistakes
- Using `os.path` functions when `pathlib` offers a cleaner, object-oriented API
- Forgetting that `suffix` includes the dot (e.g., `.txt` not `txt`)
- Assuming `anchor` and `drive` behave the same across operating systems
- Mixing `PurePath` and `Path` when you don't need filesystem access
Variations
- Use `p.suffixes` to get all extensions at once (e.g., `['.tar', '.gz']`)
- Use `PurePath` instead of `Path` when you only parse paths and never touch the filesystem
Real-world use cases
- Extracting file extensions to route different document types to the correct processor.
- Building log file rotation scripts that need parent, stem, and timestamp suffixes.
- Inspecting uploaded filenames to validate allowed file types before saving.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.