Sub topic 2
Pure paths and concrete paths
This chapter assumes you know basic Python syntax, functions, and loops. It also assumes you know what files and directories are on your operating system, and that you can use strings and print. Later chapters cover joining, taking apart, and resolving paths in detail. Here you learn the class split that explains which methods touch the disk and which do not.
Two kinds of path classes
The pathlib module has two families of classes.
- A pure path only manipulates path text. It never reads or writes the file system. Its classes are
PurePath,PurePosixPath, andPureWindowsPath. - A concrete path does everything a pure path does, and it can also query and change the file system. Its classes are
Path,PosixPath, andWindowsPath.
Every concrete class inherits from the matching pure class. A Path is therefore a PurePath with extra methods such as exists(), read_text(), and mkdir().
What you get when you call Path()
You normally write Path(...) and never name PosixPath or WindowsPath. Calling Path() returns the concrete class for your operating system.
from pathlib import Path
p = Path("data/report.csv")
print(type(p).__name__) # PosixPath on Linux and macOS, WindowsPath on Windows
print(isinstance(p, Path)) # TrueThe concrete classes match the system you run on. On Linux, WindowsPath("C:/x") raises an error when you try to create it. Windows-style paths could not be used with the file system there, so Python refuses them.
Pure paths work on any system
A pure path never touches the disk, so you can create any flavor on any operating system. This is useful when you handle paths that come from another system, such as a path in a log file or a configuration file.
from pathlib import PureWindowsPath
w = PureWindowsPath("C:/Users/ana/file.txt")
print(w.name) # file.txt
print(w.drive) # C:
print(w.parent) # C:\Users\anaThis code runs the same on Linux, macOS, and Windows. A later chapter on cross-platform handling covers this in more depth.
Which methods touch the disk
The split tells you where a call could fail because of the file system. Methods that only work on the path text are available on pure paths and cannot raise errors such as FileNotFoundError.
| Task | Available on pure paths | Needs a concrete path |
|---|---|---|
| Join with `/` | Yes | Yes |
| `name`, `stem`, `suffix`, `parent`, `parts` | Yes | Yes |
| `with_name`, `with_suffix`, `relative_to` | Yes | Yes |
| `exists`, `is_file`, `is_dir` | No | Yes |
| `read_text`, `write_text`, `mkdir` | No | Yes |
| `glob`, `rglob`, `iterdir` | No | Yes |
| `resolve`, `cwd`, `home` | No | Yes |
Deriving a new path never changes the file system, even on a concrete path:
from pathlib import Path
draft = Path("notes/draft.txt")
print(draft.with_suffix(".md")) # notes/draft.md
print(draft) # notes/draft.txtThe original draft is unchanged. Path objects are immutable, so each operation returns a new object. The file notes/draft.txt does not even need to exist for this code to work.
Common errors
- Calling a disk method on a pure path.
PurePosixPath("a").exists()raisesAttributeError, because the method is not defined on pure classes. - Expecting
Path("a.txt")to fail when the file is missing. It does not. The failure comes later, when you callread_text(). - Creating
WindowsPathon Linux or macOS, orPosixPathon Windows. Python raisesNotImplementedError. Use a pure class instead.
Exercise
You receive the string "C:\\logs\\app.log" from a Windows server, and your script runs on Linux. Which class should you use to get the file name app.log, and why not Path?
Show answer
Use PureWindowsPath("C:\\logs\\app.log").name. On Linux, Path creates a PosixPath, which treats the backslashes as ordinary characters and would return the whole string as the name. The pure class parses Windows rules without touching the disk.
Exercise
Does Path("missing/file.txt").with_suffix(".md") raise an error if the folder missing does not exist?
Show answer
No. with_suffix only builds a new path from text and never accesses the file system, so it returns Path("missing/file.md").