Skip to content

Module 15 · Python Standard Libraries — topic 7 of 13

pathlib

More pathlib: path components (parents, suffixes, stem), deriving new paths with with_suffix and with_stem, matching patterns, pure paths, and file-system operations such as rename, touch, unlink and resolve.

Beginner 8 min read·Lesson 228 of 306 in Python Programming

Learning objectives

  • Navigate path components
  • Derive new paths from existing ones
  • Rename, create and delete files with Path methods

Definition

pathlib represents file-system paths as objects. Pure paths (PurePath, PurePosixPath, PureWindowsPath) only manipulate path text; concrete Path objects can also access the file system.

Introduction

The File Handling module introduced pathlib for reading and writing. This lesson focuses on the rest of its toolbox: taking paths apart, building new ones and managing files.

Why it matters

Deriving output paths from input paths (report.csv → report.json) and managing files with methods keeps file-processing scripts short and correct.

Detailed explanation

p.parent is the containing folder; p.parents is a sequence of all ancestors, nearest first.

p.suffix is the last extension, p.suffixes all of them (['.tar', '.gz']), and p.stem the name without the last suffix.

p.with_suffix(".json"), p.with_stem("summary") and p.with_name("other.txt") return new paths; the original is unchanged.

p.match("*.py") tests a path against a glob-style pattern from the right.

Pure paths never touch the disk, so they can manipulate Windows paths on Linux and vice versa.

Concrete operations: rename (returns the new Path), replace, touch (create empty file), unlink (delete file), mkdir and rmdir.

resolve() returns an absolute path with .. and symbolic links resolved — useful for comparing paths.

Path.home() and Path.cwd() give starting points for user-specific and working-directory paths.

Syntax

Python
from pathlib import Path
src = Path("data/report.csv")
out = src.with_suffix(".json")
src.rename(src.with_stem("report-old"))
Path("log.txt").touch()
Path("log.txt").unlink()
  • Derive paths instead of editing strings.
  • Methods operate on the file system.
  • resolve for absolute paths.

Code examples

Taking a path apart

Python
from pathlib import PurePosixPath as P
p = P("/srv/app/data/report.final.csv")
print(p.suffixes, p.stem, p.with_suffix(".json").name, p.with_stem("summary").name)
print([str(x) for x in p.parents][:3])
Output
['.final', '.csv'] report.final report.final.json summary.csv
['/srv/app/data', '/srv/app', '/srv']

Matching patterns

Python
from pathlib import PurePosixPath as P
for name in ["src/app.py", "tests/test_app.py", "README.md"]:
print(name, P(name).match("*.py"), P(name).match("tests/*.py"))
Output
src/app.py True False
tests/test_app.py True True
README.md False False

More examples

Managing files with Path methods

Python
from pathlib import Path
base = Path("workspace")
(base / "drafts").mkdir(parents=True)
draft = base / "drafts" / "essay.txt"
draft.write_text("first draft", encoding="utf-8")
final = draft.rename(base / "essay_final.txt")
print(draft.exists(), final.exists(), final.read_text(encoding="utf-8"))
(base / "notes.md").touch()
print(sorted(p.name for p in base.iterdir()))
final.unlink()
(base / "notes.md").unlink()
(base / "drafts").rmdir()
print(list(base.iterdir()))
print(Path("workspace/../workspace").resolve() == base.resolve())
Output
False True first draft
['drafts', 'essay_final.txt', 'notes.md']
[]
True

Step-by-step explanation

  • rename moves the file and returns its new path; the old path no longer exists.
  • touch creates an empty file, and unlink and rmdir clean up.
  • resolve normalises .. so two spellings of the same folder compare equal.

Expected output

Running “Managing files with Path methods” prints exactly:

TextOutput
False True first draft
['drafts', 'essay_final.txt', 'notes.md']
[]
True

Practical applications

  • Converting every .md file to a .html file with the same stem.
  • Archiving processed files by renaming them.

Best practices

  • Use with_suffix/with_stem to derive paths.
  • Use pure paths for path text from other systems.
  • Compare resolved paths.

Common mistakes

String slicing for extensions

Avoid

out = name[:-4] + ".json"

Prefer

out = Path(name).with_suffix(".json")

Slicing breaks for extensions that aren't three letters long.

Important notes

  • Path.walk() (Python 3.12+) is pathlib's version of os.walk.

Key takeaways

  • parents, suffixes and stem take paths apart.
  • with_* methods build related paths.
  • Path methods rename, create and delete files.

Try it yourself

  1. 1
    For every .txt file in a folder, create an empty .bak file with the same stem.
  2. 2
    Print all ancestors of the current working directory.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

14 questions cover the “Python Standard Libraries” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhy call random.seed(42) before generating numbers in a test?
  • ModerateWhat is printed?
Practise this module