Sub topic 2
Pure paths and concrete paths
This chapter assumes you know the basics of Path objects from the previous chapter, Python 3.9 or later, and what a file system is. By the end you should know which pathlib classes only work on path text, which ones also talk to the disk, and when to choose each.
Two layers in one module
The pathlib module has two kinds of classes:
- Pure paths are objects that only manipulate path text. They never read or write the file system, so they behave the same on any machine.
- Concrete paths are pure paths that can also query and change the file system. They are the classes you use most of the time.
Path is the concrete class you already know. It inherits everything from a pure class and adds methods such as exists(), read_text(), and mkdir().
The class hierarchy
There are six classes. PurePath is the base of all of them. Each operating system family has its own flavor of pure path, and each concrete class combines Path with one of those flavors.
When you call Path("data"), pathlib picks the concrete class that matches the running system. The same rule applies to PurePath, which gives you the pure flavor of the current system.
from pathlib import Path, PurePath
print(type(Path("data"))) # PosixPath on Linux and macOS, WindowsPath on Windows
print(type(PurePath("data"))) # PurePosixPath on Linux and macOS, PureWindowsPath on WindowsWhat a pure path can do
A pure path supports every operation that needs only the text of the path:
- Joining with
/. - Reading
name,stem,suffix,parent,parts,drive, andanchor. - Deriving new paths with
with_name(),with_suffix(), andrelative_to(). - Checking
is_absolute(),is_relative_to(), andmatch(). - Converting with
str(),as_posix(), andas_uri().
None of these asks the operating system anything. A pure path can name a file that does not exist, on a drive that your machine does not have.
Here is a pure Windows path parsed on any system:
from pathlib import PurePosixPath, PureWindowsPath
w = PureWindowsPath(r"C:\data\Reports\Q1.CSV")
print(w.drive) # C:
print(w.suffix) # .CSV
print(w.parts) # ('C:\\', 'data', 'Reports', 'Q1.CSV')
print(w.as_posix()) # C:/data/Reports/Q1.CSV
# Rebuild the part after the drive as a POSIX path.
print(PurePosixPath(*w.parts[1:])) # data/Reports/Q1.CSVThis is useful when a log file, a configuration file, or a zip archive written on Windows gets processed on a Linux server. A plain Path on Linux would treat the backslashes as ordinary characters in a file name. PureWindowsPath parses them as separators.
What a concrete path adds
A concrete path inherits all of the above and adds methods that call the operating system. Some examples:
- Querying:
exists(),is_file(),is_dir(),stat(),samefile(). - Reading and writing:
read_text(),write_text(),read_bytes(),write_bytes(),open(). - Changing:
mkdir(),rename(),unlink(),rmdir(). - Listing:
iterdir(),glob(),rglob(). - Resolving:
resolve(),absolute(),expanduser(), and the class methodsPath.cwd()andPath.home().
Calling one of these methods on a pure path fails right away:
from pathlib import PurePosixPath
p = PurePosixPath("notes/todo.txt")
try:
p.exists()
except AttributeError as err:
print("pure paths have no file system methods:", err)The method does not exist on the class, so you get AttributeError and not a quiet False. That makes accidental file system access in pure code easy to find.
Creating a concrete path does not touch the disk
A common misunderstanding is that Path("report.txt") opens or checks something. It does not. The object is created from the text alone, and the file system is consulted only when you call a method that needs it.
from pathlib import Path
missing = Path("this_file_does_not_exist.txt")
print(missing) # this_file_does_not_exist.txt
print(missing.exists()) # False
try:
missing.read_text(encoding="utf-8")
except FileNotFoundError:
print("reading failed, but creating the Path did not")Note that exists() returns False for a missing file and does not raise. read_text() raises FileNotFoundError. The next chapters cover this difference in detail.
You cannot create the wrong concrete flavor
Concrete classes are tied to the system they run on. On Linux or macOS you cannot instantiate WindowsPath, because its methods would have to call Windows file system functions that do not exist there. The reverse is also true.
from pathlib import WindowsPath
try:
p = WindowsPath("C:/Users/ana")
print("running on Windows:", p)
except NotImplementedError:
print("WindowsPath is not available on this system")On Linux and macOS this prints the second message. On Windows it prints the first. Pure classes have no such limit. All four pure-path constructors work on every system, and that is the point of having them.
Comparing the two layers
| Feature | Pure path | Concrete path |
|---|---|---|
| Classes | `PurePath`, `PurePosixPath`, `PureWindowsPath` | `Path`, `PosixPath`, `WindowsPath` |
| Touches the file system | Never | Only in methods that need it |
| Parses and joins path text | Yes | Yes, inherited |
| `exists()`, `read_text()`, `mkdir()` | Not available | Available |
| Works with any flavor on any OS | Yes | Only the flavor of the current OS |
| Typical use | Parsing foreign paths, testing path logic | Everyday file work |
Flavor rules that affect behavior
The flavor decides how text is parsed and compared. Three differences matter in practice.
Separators. PureWindowsPath accepts both / and \ as separators and prints with \. PurePosixPath accepts only /.
Case sensitivity. Windows paths compare without regard to case. POSIX paths are case-sensitive.
from pathlib import PurePosixPath, PureWindowsPath
print(PureWindowsPath("C:/Data/Q1.csv") == PureWindowsPath("c:/data/q1.CSV")) # True
print(PurePosixPath("Data/q1.csv") == PurePosixPath("data/q1.csv")) # FalseMeaning of "absolute". A Windows path needs a drive (or a network share) to be absolute. A POSIX path needs a leading /.
from pathlib import PurePosixPath, PureWindowsPath
print(PureWindowsPath("/data").is_absolute()) # False: no drive
print(PureWindowsPath("C:/data").is_absolute()) # True
print(PurePosixPath("C:/data").is_absolute()) # False: POSIX has no drivesObjects of different flavors are never equal, and you cannot sort them together:
from pathlib import PurePosixPath, PureWindowsPath
a = PurePosixPath("docs")
b = PureWindowsPath("docs")
print(a == b) # False
try:
a < b
except TypeError:
print("different flavors cannot be ordered")Using pure paths to test path logic
Because pure paths need no files, they let you write functions that work on path values and test them on any machine. Annotate parameters with PurePath, and the function accepts both pure and concrete paths, since Path is a subclass.
from pathlib import PurePath, PurePosixPath, PureWindowsPath
def output_for(source: PurePath, out_root: PurePath) -> PurePath:
"""Return where the Markdown version of a source file should go."""
return out_root / (source.stem + ".md")
print(output_for(PurePosixPath("/srv/docs/a.txt"), PurePosixPath("/out")))
# /out/a.md
print(output_for(PureWindowsPath("C:/docs/a.txt"), PureWindowsPath("D:/out")))
# D:\out\a.mdThe function never opens a file, so a test needs no temporary directories and no cleanup. You can check Windows behavior from a Linux test runner.
Choosing between them
Use these criteria:
- Use
Pathwhen you will read, write, list, or check real files on the machine running the code. - Use
PurePosixPathorPureWindowsPathwhen the path comes from another system, such as an archive entry, a URL path, or a remote server, and you must parse it as that system would. - Use
PurePathas an annotation for functions that only need path text. - Convert from pure to concrete only at the point where you need file access, for example with
Path(pure_path.as_posix())after you have confirmed the path is valid for this system.
Exercise
A script running on Linux receives the string r"D:\logs\2026\app.LOG" from a Windows agent. Which class should you use to read its suffix, and what does .suffix return? Why can you not call exists() on the result, and why would plain Path give a wrong answer for .parent?
Show answer
Use PureWindowsPath. Its .suffix returns '.LOG', with the original case kept. A pure path has no exists() method, and the file lives on another machine, so there is nothing to check locally. Plain Path on Linux is a PosixPath, which treats backslashes as normal characters. The whole string is then a single file name with no parent directories, so .parent returns '.' instead of 'D:\logs\2026'.
Exercise
What is the difference between Path("a.txt").exists() returning False and Path("a.txt").read_text() when the file is missing? Does creating Path("a.txt") itself ever fail because the file is missing?
Show answer
exists() reports the absence by returning False, while read_text() raises FileNotFoundError. Creating Path("a.txt") never fails for a missing file, because constructing a path only stores text and does not touch the file system.