File system · 1 / 15 Theory

Paths as objects: pathlib

When your programs handle real files, writing paths as text (“folder/ + name”) is a source of errors: different separators depending on the system, extra or missing slashes… The pathlib module represents each path as an object with attributes and methods.

from pathlib import Path, PurePosixPath

path = PurePosixPath("/home/ana/docs/report.final.txt")
print(path.name)        # report.final.txt
print(path.stem)        # report.final
print(path.suffix)      # .txt
print(path.parent)      # /home/ana/docs
print(path.parts)       # ('/', 'home', 'ana', 'docs', 'report.final.txt')

folder = PurePosixPath("project")
print(folder / "src" / "main.py")             # project/src/main.py   (the / operator joins paths)
print(path.with_suffix(".md"))                 # /home/ana/docs/report.final.md
print(path.with_name("notes.txt"))             # /home/ana/docs/notes.txt
print(path.relative_to("/home/ana"))           # docs/report.final.txt

# Path = the same, but tied to the real file system:
print(Path("missing.txt").exists())          # False
  • Path works with the real disk; PurePosixPath / PureWindowsPath only manipulate the text of the path, without checking whether it exists (useful to analyze paths).
  • The / operator joins pieces and uses the right separator for each system.
  • name, stem, suffix, parent and parts split a path; with_suffix, with_name and relative_to create another.
  • suffix only returns the last extension: report.tar.gz → .gz; suffixes returns all of them.
  • A path can be relative (data/a.txt, with respect to the working folder) or absolute (/home/ana/a.txt); resolve() turns it into absolute.

You practice it in Name, extension and folder.