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:
- 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:/')
- The
suffix
property only returns the final suffix, so the suffix ofmycoolfile.tar.gz
is just.gz
. Use.suffixes
to get a list of the suffixes in the path:['.tar', '.gz']