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.

Easy Python 3.9+ Aug 9, 2026 Files & data 14 views 0 copies

Python code

12 lines
Python 3.9+
from 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

stdout
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

  1. Use `p.suffixes` to get all extensions at once (e.g., `['.tar', '.gz']`)
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.