Python pathlib Cheat Sheet

Apr 27, 2025

I seem to have trouble remembering all of the various variables and identifiers in Python's pathlib library, so I'm making myself a cheat sheet for future reference.

from pathlib import Path

# A target path that we want to operate on
path = Path("C:/Repos/myproject/mycoolfile.7z")

# path.parts ==> ('C:\\', 'Repos', 'myproject', 'mycoolfile.7z')
# path.drive ==> 'C:'
# path.root ==> '\\'
# path.anchor ==> 'C:\\'
# path.parents ==> Immutable sequence; see note #1 below
# path.parent ==> WindowsPath("C:/Repos/myproject")
# path.name ==> 'mycoolfile.7z'
# path.suffix ==> '.7z'; see note #2 below
# path.stem ==> 'mycoolfile'

A few notes:

  1. The parents property returns an immutable sequence of the parents. In the example above, the result would be:
    • WindowsPath('C:/Repos/myproject')
    • WindowsPath('C:/Repos')
    • WindowsPath('C:/')
  2. The suffix property only returns the final suffix, so the suffix of mycoolfile.tar.gz is just .gz. Use .suffixes to get a list of the suffixes in the path: ['.tar', '.gz']

No comments (yet!)

Leave a Comment

Ignore this field:
Never displayed
Leave this blank:
Optional; will not be indexed
Ignore this field:
Both Markdown and a limited set of HTML tags are supported
Leave this empty: