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.
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
- Derive paths instead of editing strings.
- Methods operate on the file system.
- resolve for absolute paths.
Code examples
Taking a path apart
['.final', '.csv'] report.final report.final.json summary.csv ['/srv/app/data', '/srv/app', '/srv']
Matching patterns
src/app.py True False tests/test_app.py True True README.md False False
More examples
Managing files with Path methods
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:
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
Prefer
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
- 1For every .txt file in a folder, create an empty .bak file with the same stem.
- 2Print 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?