Python

Python pathlib — Joining Paths, Parts, Glob, and Files

A program that works with files spends half its file code on the paths themselves: joining a folder and a file name, taking a name apart, finding every matching file in a tree, and moving a result to its final name. The pathlib module in the standard library does that work with one Path object instead of string cutting. This guide builds a path one piece at a time: joining first, then the parts of a path, the folders above it, whole-file reading and writing, listing and searching a tree, renaming, and the errors a missing file or a bad suffix raises. Each step is a small working program with the exact output it prints.

Written November 13, 2026 · Tested with Python 3.12.3 · 12 min read

By the end of this guide
  • The main program: build a path and take it apart
  • Absolute paths, and the segment that replaces
  • Parents, and changing a name or a suffix
  • On disk: create, write, read, and measure

Written November 13, 2026

Tested with Python 3.12.3

What this guide is

A Path is an object that holds a file or folder location and knows how that location is put together. You build one from a string, join more pieces onto it with the slash operator, and ask it for its parts: the final name, the name without its suffix, the suffix itself, and the folder that holds it. The same object can then do the file work: create a folder, write or read a whole small file, list what a folder holds, find files that match a pattern, and rename or delete a file. None of the joining or splitting touches the disk. Only the methods that create, read, write, list, rename, or delete do. Keeping those two groups apart is the main idea: you can build and check a path long before any file exists at that location.

The main program: build a path and take it apart

The slash operator joins a path and a new piece. Each join returns a new Path, and the pieces can be strings. Printing a Path shows the joined location with the separator for the system the program runs on, which is a forward slash in the output here:

Python
from pathlib import Path
p = Path("reports") / "2026" / "summary.txt"
print(p)
print(str(p))
print(p.name)
print(p.stem)
print(p.suffix)
print(p.parent)
print(p.parts)
print(p.is_absolute())

The exact output:

Output
reports/2026/summary.txt
reports/2026/summary.txt
summary.txt
summary
.txt
reports/2026
('reports', '2026', 'summary.txt')
False

The name is the last piece alone. The stem is that name with its final suffix removed, and the suffix starts with a dot. The parent is everything before the name, as a Path of its own, so a parent can be joined and split again. The parts tuple lists every piece in order. This path is not absolute, because it does not start from the root of the file system. It names a location relative to whatever folder the program runs in.

Absolute paths, and the segment that replaces

A path that starts with a slash is absolute: it names a location from the root, with no dependence on the folder the program runs in. The anchor is that starting slash. Joining works the same on an absolute path, until the piece being joined is itself absolute. Then the earlier path is dropped and the new piece wins:

Python
from pathlib import Path
p = Path("/home") / "ana" / "notes.txt"
print(p.is_absolute())
print(p.anchor)
q = Path("notes.txt")
print(q.is_absolute())
r = p / "extra.txt"
print(r)
s = p / "/etc/hosts"
print(s)

The exact output:

Output
True
/
False
/home/ana/notes.txt/extra.txt
/etc/hosts

The third join looks like a mistake and is worth remembering as one. A program that joins a fixed folder with a name supplied from outside, such as a file name from a user or from a data file, can end up pointing at a completely different location if that name starts with a slash. Checking a supplied name with is_absolute before joining it is the guard. The relative name in the second part of the program reports False, so a plain file name is safe to join.

Parents, and changing a name or a suffix

The parent is the folder directly above a path. The parents sequence keeps going upward, one folder at a time, ending at the current folder for a relative path. Three methods return a changed copy of a path without touching the disk. The with_name method swaps the final piece, with_stem swaps the name without its suffix, and with_suffix swaps or removes the suffix:

Python
from pathlib import Path
p = Path("a/b/c/report.txt")
print(list(p.parents))
print(p.parent)
print(p.parents[1])
print(p.with_name("summary.txt"))
print(p.with_stem("final"))
print(p.with_suffix(".md"))
print(Path("archive.tar.gz").suffixes)
print(Path("archive.tar.gz").with_suffix(".zip"))

The exact output:

Output
[PosixPath('a/b/c'), PosixPath('a/b'), PosixPath('a'), PosixPath('.')]
a/b/c
a/b
a/b/c/summary.txt
a/b/c/final.txt
a/b/c/report.md
['.tar', '.gz']
archive.tar.zip

Two details matter in real work. First, the list of parents prints each entry as a PosixPath, the name of the Path type on this system. The values are paths, not strings, and they can be joined and tested like any other Path. Second, a file can carry more than one suffix. The suffixes list shows both parts of archive.tar.gz, while suffix alone would show only .gz. Changing the suffix therefore changes only the last one, which is why the result is archive.tar.zip and not archive.zip. Code that renames downloads or build results needs that rule before it promises a new name.

On disk: create, write, read, and measure

So far nothing exists on disk. The mkdir method creates a folder, write_text creates or replaces a whole small file, and read_text returns its full content as a string. The exists, is_file, and is_dir methods report what is at a location right now, and stat gives facts about a file, including its size in bytes:

Python
from pathlib import Path
root = Path("work")
root.mkdir()
p = root / "notes.txt"
print(p.exists(), p.is_file(), p.is_dir())
print(root.exists(), root.is_dir())
p.write_text("one\ntwo\n", encoding="utf-8")
print(p.exists(), p.is_file())
print(p.read_text(encoding="utf-8"), end="")
print("size:", p.stat().st_size)
print(root.is_absolute())

The exact output:

Output
False False False
True True
True True
one
two
size: 8
False

Before the write, the file path reports False for all three questions, because nothing is there. The folder reports True once mkdir has run. The size is 8 bytes: two words of three letters, each followed by a newline. The write_text and read_text methods take the same encoding argument as open, so the habit from file work carries over. These two methods suit a small file you want whole. For a large file, open the Path and read it a line at a time instead, so the whole file never sits in memory at once.

Listing a folder, and finding files in a tree

The iterdir method yields every entry in one folder, in the order the system returns them, with files and folders mixed together. Sorting the names makes the output stable. The glob method finds entries that match a pattern in one folder, and rglob finds matches in that folder and in every folder below it:

Python
from pathlib import Path
root = Path("data")
(root / "sub").mkdir(parents=True)
for name in ["b.txt", "a.txt", "c.md"]:
    (root / name).write_text(name, encoding="utf-8")
(root / "sub" / "d.txt").write_text("d", encoding="utf-8")
print(sorted(x.name for x in root.iterdir()))
print(sorted(str(x) for x in root.glob("*.txt")))
print(sorted(str(x) for x in root.rglob("*.txt")))
print(sorted(x.name for x in root.iterdir() if x.is_dir()))

The exact output:

Config
['a.txt', 'b.txt', 'c.md', 'sub']
['data/a.txt', 'data/b.txt']
['data/a.txt', 'data/b.txt', 'data/sub/d.txt']
['sub']

The glob result holds only the two text files directly in data. The rglob result adds the text file inside sub, because the search descends. The .md file matches neither pattern. The last line filters a listing down to folders alone by asking each entry whether it is a directory. The parents=True argument on mkdir creates any missing folders above sub as well as sub itself, which is the form to use when a program builds a nested output folder that may not exist yet. Sorting is doing real work in each print: without it, the order belongs to the file system and can differ between machines and between runs.

Renaming, replacing, and deleting

The rename method moves a file to a new path and returns that new path. The original path no longer exists once the rename has run. The replace method is the same move with one difference in intent: it is the form to reach for when the target name may already be taken and overwriting it is the plan. The unlink method deletes a file:

Python
from pathlib import Path
p = Path("old.txt")
p.write_text("data", encoding="utf-8")
q = p.rename("new.txt")
print(type(q).__name__, q)
print(p.exists(), q.exists())
print(q.read_text(encoding="utf-8"))
q.replace("final.txt")
print(q.exists(), Path("final.txt").exists())
Path("final.txt").unlink()
print(Path("final.txt").exists())

The exact output:

Output
PosixPath new.txt
False True
data
False True
False

The type name prints as PosixPath, the system-specific Path type. The content survives the rename unchanged, because the file itself moved; nothing was copied. After replace, the new.txt path reports False and final.txt reports True. The final unlink removes that file, and the last check reports False. A rename inside one folder is a cheap operation. Treating it as a copy would waste time on a large file and would leave the old file behind as a stale duplicate.

Two errors, and a safe way to test a prefix

Reading a file that does not exist raises FileNotFoundError, the same error open raises. Changing a suffix has its own rule: the new suffix must start with a dot, or be empty to remove the suffix, and any other form raises ValueError. The is_relative_to method tests whether one path sits under another, and returns a plain True or False instead of raising:

Python
from pathlib import Path
p = Path("missing.txt")
print(p.exists())
try:
    p.read_text(encoding="utf-8")
except FileNotFoundError as e:
    print(f"FileNotFoundError: {e}")
try:
    Path("noext").with_suffix("")
    print("empty suffix ok")
    print(Path("file.txt").with_suffix(""))
except ValueError as e:
    print(f"ValueError: {e}")
try:
    Path("file.txt").with_suffix("md")
except ValueError as e:
    print(f"ValueError: {e}")
print(Path("a/b.txt").is_relative_to("a"))
print(Path("a/b.txt").is_relative_to("c"))

The exact output:

Output
False
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
empty suffix ok
file
ValueError: Invalid suffix 'md'
True
False

An empty suffix is allowed and removes the suffix, leaving the stem as the whole name. A suffix without its dot is not allowed. That small rule explains a common first error with this method: with_suffix takes .md, not md. The prefix test at the end is the safe companion to the absolute-segment trap shown earlier. Before a program opens a path built from outside input, it can test that the result is still relative to the folder it was meant to stay inside, and refuse the ones that are not.

Which form for which job

Job Form Why
Join a folder and a file name The slash operator on a Path The separator and the parts are handled for you
Get a file name, stem, or suffix name, stem, suffix, suffixes No string cutting, and multi-suffix names are handled
Move up one or more folders parent, or parents by index Each value is still a Path you can join
Rename a result before it exists with_name, with_stem, with_suffix A new Path is returned, and nothing on disk changes
Create a nested folder mkdir with parents=True Missing folders above the target are created too
Read or write a small file whole read_text, write_text, with an encoding One call opens, moves the text, and closes
List one folder iterdir, sorted for stable order Files and folders arrive together, in system order
Find files in a tree rglob with a pattern The search descends into every folder below
Move a file to its final name rename, or replace to overwrite The file moves, and no copy is made
Delete a file unlink The path reports False from exists after the delete
Keep outside input inside a folder is_absolute and is_relative_to checks An absolute or escaping name is refused before opening

Checklist

  • Before joining a path with a name from outside the program, check that name with is_absolute, because an absolute piece replaces the whole path.
  • Before reading a path, ask exists or be ready to catch FileNotFoundError; building a Path does not create anything.
  • Before calling with_suffix, include the dot, and remember that only the last suffix changes on a name like archive.tar.gz.
  • Before listing or globbing in output a reader will compare, sort the results; the raw order belongs to the file system.
  • Before writing a whole file with write_text, ask how large it can get; open and write in pieces when the size is not under your control.
  • Before renaming a file a later step still looks for under its old name, update that step; rename moves the file, and the old path is gone.

Sources

Keep Exploring