Sub topic 4
Taking paths apart: name, stem, suffix, parent, parts
A Path object stores a path as a sequence of components, not as one string. You read those components through attributes, so you never need str.split("/"), rsplit(".", 1), or slicing. This chapter covers each attribute and its edge cases, and the mistakes that come from misreading them.
It assumes you can create a Path and join segments with /, which earlier chapters cover. You also need to be comfortable with tuples, sequences, and indexing. Every example here uses string manipulation only, so none of it touches the file system.
The component model
Every path breaks into an optional anchor (a drive, a root, or both) followed by zero or more named segments. The last segment is the name. Everything before the name is the parent.
| Attribute | Type | Meaning |
|---|---|---|
| `name` | `str` | Final component, or `""` if there is none |
| `stem` | `str` | `name` without its last suffix |
| `suffix` | `str` | Last dot-separated extension, including the dot |
| `suffixes` | `list[str]` | Every extension in `name` |
| `parent` | `Path` | The path without its final component |
| `parents` | sequence of `Path` | All ancestors, nearest first |
| `parts` | `tuple[str, ...]` | Anchor (if any) plus each component |
| `drive`, `root`, `anchor` | `str` | The anchor and its pieces |
These are properties, not methods. Write p.name, not p.name(). Calling it fails with TypeError: 'str' object is not callable.
name, stem, suffix, and suffixes
from pathlib import Path
p = Path("/home/ana/archive/report.final.tar.gz")
print(p.name) # report.final.tar.gz
print(p.stem) # report.final.tar
print(p.suffix) # .gz
print(p.suffixes) # ['.final', '.tar', '.gz']
print(p.parent) # /home/ana/archive
print(p.parts) # ('/', 'home', 'ana', 'archive', 'report.final.tar.gz')stem and suffix split name at the last dot only. This is why stem still contains .tar. suffixes lists every dot-separated piece after the first character of the name.
Edge cases in names
Run these to see how the rules apply to unusual names.
from pathlib import PurePosixPath
for text in [".bashrc", "README", "archive.tar.gz", "a/b/", ".", "..", "/"]:
p = PurePosixPath(text)
print(repr(text), "->", repr(p.name), repr(p.stem), repr(p.suffix))The output is:
'.bashrc' -> '.bashrc' '.bashrc' ''
'README' -> 'README' 'README' ''
'archive.tar.gz' -> 'archive.tar.gz' 'archive.tar' '.gz'
'a/b/' -> 'b' 'b' ''
'.' -> '' '' ''
'..' -> '..' '..' ''
'/' -> '' '' ''- A leading dot marks a hidden file on POSIX systems, not an extension.
.bashrchas no suffix. - A trailing slash is discarded when the path is parsed.
Path("a/b/")is the same asPath("a/b"). Path(".")andPath("/")have an empty name. Code that assumesnameis never empty will fail on them.".."is a real name.pathlibdoes not collapse it, because doing so would be wrong when symbolic links are involved.
Why suffixes can mislead
suffixes splits on every dot, whether or not the dot starts a real extension.
from pathlib import Path
print(Path("backup-v1.2.tar.gz").suffixes) # ['.2', '.tar', '.gz']
print(Path("data.2026-11-26.csv").suffixes) # ['.2026-11-26', '.csv']Neither .2 nor .2026-11-26 is an extension. When you need to strip a compound extension, match the extensions you expect instead of trusting suffixes.
from pathlib import Path
COMPOUND = (".tar.gz", ".tar.bz2", ".tar.xz")
def base_name(path: Path) -> str:
"""Return the file name without its extension, honoring compound ones."""
name = path.name
for ext in COMPOUND:
if name.endswith(ext):
return name[: -len(ext)]
return path.stem
print(base_name(Path("backup-v1.2.tar.gz"))) # backup-v1.2
print(base_name(Path("notes.txt"))) # notesCase and comparison
suffix keeps the original case, so .PY and .py are different strings. On POSIX these are different files. On Windows the file system ignores case. When you group or filter by extension, call .lower() on the suffix.
from collections import Counter
from pathlib import PurePosixPath
names = ["src/app.py", "src/utils.PY", "README", "docs/guide.md", "docs/.hidden", "setup.py"]
counts = Counter(PurePosixPath(n).suffix.lower() or "(none)" for n in names)
print(sorted(counts.items())) # [('(none)', 2), ('.md', 1), ('.py', 3)]The or "(none)" handles empty suffixes, which are common.
parent and parents
parent is a new Path with the last component removed. It is purely lexical. It does not look at the disk and does not resolve ...
from pathlib import PurePosixPath
log = PurePosixPath("/srv/app/logs/app.log")
print(log.parent) # /srv/app/logs
print(log.parent.parent) # /srv/app
print(list(log.parents))
# [PurePosixPath('/srv/app/logs'), PurePosixPath('/srv/app'), PurePosixPath('/srv'), PurePosixPath('/')]
print(log.parents[1]) # /srv/app
print(log.parents[-1]) # /parents is a read-only sequence. It supports indexing and iteration, and since Python 3.10 it also supports negative indices and slices. On older versions, use list(p.parents)[-1].
Two boundary cases matter in loops that walk upward:
- The parent of a root is the root itself:
PurePosixPath("/").parentis/. - The parent of a single relative name is
.:PurePosixPath("file.txt").parentis..
A loop of the form while p.name: stops at both. A loop of the form while p != p.parent: also stops at both, because each one is its own parent.
from pathlib import PurePosixPath
def find_upward(start: PurePosixPath, marker_names: set[str]) -> PurePosixPath | None:
"""Return the nearest ancestor (or start) whose name is in marker_names."""
for candidate in [start, *start.parents]:
if candidate.name in marker_names:
return candidate
return None
print(find_upward(PurePosixPath("/work/project/src/pkg"), {"project"})) # /work/projectThis walks upward without any special handling for the top, because parents ends by itself.
parts, drive, root, and anchor
parts returns a tuple. On POSIX, an absolute path starts with '/' as its first element.
from pathlib import PurePosixPath
print(PurePosixPath("/usr/local/bin").parts) # ('/', 'usr', 'local', 'bin')
print(PurePosixPath("usr/local/bin").parts) # ('usr', 'local', 'bin')
print(PurePosixPath("a//b/./c/../d").parts) # ('a', 'b', 'c', '..', 'd')The last line shows normalization at parse time. Repeated slashes collapse and single . segments disappear. .. is kept.
Because the anchor counts as an element, the number of parts differs between absolute and relative paths. To count only the named directories, remove the anchor first.
from pathlib import PurePosixPath
p = PurePosixPath("/usr/local/bin")
print(len(p.parts)) # 4
print(len(p.parts) - bool(p.anchor)) # 3
print(p.parts[len(p.anchor) > 0:]) # ('usr', 'local', 'bin')On Windows paths the anchor has more structure. PureWindowsPath lets you inspect it on any operating system.
from pathlib import PureWindowsPath
w = PureWindowsPath("C:/Users/ana/file.txt")
print(w.name) # file.txt
print(w.drive) # C:
print(w.root) # \
print(w.anchor) # C:\
print(w.parts) # ('C:\\', 'Users', 'ana', 'file.txt')
print(w.parent) # C:\Users\anaA UNC path such as //server/share/dir/f.txt has the drive \\server\share. A path like C:file.txt has a drive but no root, which means "relative to the current directory on drive C".
Common errors
- Assuming
suffixcovers compound extensions. Fordata.tar.gzit gives.gz. Usesuffixesor an explicit list. - Assuming
stemis the base name.Path("a.tar.gz").stemisa.tar. - Treating a dotfile as having an extension.
Path(".gitignore").suffixis empty. - Expecting
parentto read the disk. It never does.Path("a/b/../c").parentisa/b/.., nota. Resolve the path first if you want the real location. - Using
parts[0]as the first directory name. For absolute paths it is the anchor. - Trying to assign.
p.name = "x"raisesAttributeError, because paths are immutable. Usewith_nameandwith_suffix, which the next chapter covers.
Exercise
For Path("/data/export.2026.csv.gz"), what are the values of name, stem, suffix, and suffixes, and why is suffixes a poor way to find the "real" extension here?
Show answer
name is "export.2026.csv.gz", stem is "export.2026.csv", suffix is ".gz", and suffixes is ['.2026', '.csv', '.gz']. suffixes treats every dot as the start of an extension, so ".2026" appears even though it is part of the base name. To find the real compound extension, check name against an explicit list such as (".csv.gz", ".tar.gz").
Exercise
Using PurePosixPath, what do these expressions return: PurePosixPath("/").name, PurePosixPath("/").parent, PurePosixPath("notes.txt").parent, and len(PurePosixPath("/a/b").parts)?
Show answer
PurePosixPath("/").name is "" (an empty string). PurePosixPath("/").parent is PurePosixPath("/"), since the root is its own parent. PurePosixPath("notes.txt").parent is PurePosixPath("."). len(PurePosixPath("/a/b").parts) is 3, because parts is ('/', 'a', 'b') and the anchor counts as one element.