Sub topic 13
Handling Windows and POSIX paths on any system
This chapter assumes you know the basics from earlier chapters: building paths with /, reading name, suffix and parent, and the split between pure paths and concrete paths. Here you will use that split to work with paths from a different operating system than the one your code runs on.
Why you need foreign-flavor paths
A Path object always matches the system it runs on. On Linux and macOS you get a PosixPath. On Windows you get a WindowsPath. That is what you want when you touch real files.
Some programs handle paths that never touch the local disk:
- A Linux server parses log lines that contain Windows paths.
- A build tool reads a manifest written on another platform.
- A test suite checks Windows path logic on a Linux CI machine.
- An archive reader validates member names before extracting them.
Raw string handling with split("/") breaks here, because Windows accepts both / and \ and has drive letters. The pure path classes solve this. They parse and manipulate a specific flavor of path and never touch the file system, so they work on any operating system.
The class hierarchy
Pure classes hold the parsing rules. Concrete classes add file system methods on top.
PurePosixPath and PureWindowsPath can be created on any system. PosixPath and WindowsPath can only be created on a matching system. Calling WindowsPath("C:/x") on Linux raises NotImplementedError. Python 3.13 raises UnsupportedOperation, which is a subclass of NotImplementedError.
from pathlib import WindowsPath
try:
WindowsPath("C:/x")
except NotImplementedError as exc:
print(exc) # On Linux: cannot instantiate 'WindowsPath' on your systemOn Windows this code succeeds and prints nothing.
Parsing a Windows path on any system
The components you already know work the same way. The Windows flavor adds a drive and a root.
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\ana
print(w.root) # \
print(w.anchor) # C:\
print(w.parts) # ('C:\\', 'Users', 'ana', 'file.txt')The anchor is the drive plus the root. It is also the first item in parts. The path was written with forward slashes, and pathlib normalized it to backslashes.
Network (UNC) paths put the server and share into the drive:
from pathlib import PureWindowsPath
unc = PureWindowsPath("//server/share/reports/q1.csv")
print(unc.drive) # \\server\share
print(unc.name) # q1.csv
print(unc.parts) # ('\\\\server\\share\\', 'reports', 'q1.csv')Where the two flavors differ
| Behavior | `PurePosixPath` | `PureWindowsPath` |
|---|---|---|
| Separator when printing | `/` | `\` |
| Accepted separators when parsing | `/` only | `/` and `\` |
| Comparison | Case-sensitive | Case-insensitive |
| Drive and UNC share | None | Yes, such as `C:` |
| Reserved names such as `NUL` | No | Yes, see `is_reserved()` |
The is_reserved() method exists on PureWindowsPath. Python 3.13 deprecates it in favor of os.path.isreserved().
The differences show up in a few short checks:
from pathlib import PurePosixPath, PureWindowsPath
print(PureWindowsPath("a/b/c")) # a\b\c
print(PurePosixPath("a\\b").parts) # ('a\\b',)
print(PureWindowsPath("a\\b").parts) # ('a', 'b')
print(PureWindowsPath("C:/Users") == PureWindowsPath("c:\\users")) # True
print(PurePosixPath("Users") == PurePosixPath("users")) # False
print(PurePosixPath("a") == PureWindowsPath("a")) # FalseLook at line two. In the POSIX flavor, a backslash is an ordinary filename character, so a\b is a single component. The same text is two components in the Windows flavor.
Paths of different flavors are never equal. Sorting them against each other with < raises TypeError. Windows-flavor equality and hashing ignore case, so PureWindowsPath objects work as dictionary keys without extra normalizing.
Methods that stay and methods that go
Pure paths keep every method that only manipulates text: with_name, with_suffix, relative_to, joinpath, /, parents, match, and is_absolute.
They lose every method that needs a file system: exists, is_file, read_text, mkdir, glob, resolve, and the rest. Calling one raises AttributeError. This failure is intended. A pure path cannot silently touch the wrong disk.
from pathlib import PureWindowsPath
p = PureWindowsPath("C:/Users/ana/Docs/Report.TXT")
print(p.with_suffix(".md")) # C:\Users\ana\Docs\Report.md
print(p.relative_to("c:/users")) # ana\Docs\Report.TXT
print(PureWindowsPath("README.TXT").match("*.txt")) # TrueThe relative_to call succeeds even though the case of users differs, because the Windows flavor compares case-insensitively.
Absolute paths depend on the flavor
Whether a path counts as absolute depends on the flavor that parses it:
from pathlib import PurePosixPath, PureWindowsPath
print(PureWindowsPath("C:/data").is_absolute()) # True
print(PureWindowsPath("/data").is_absolute()) # False
print(PureWindowsPath("C:data").is_absolute()) # False
print(PurePosixPath("C:/data").is_absolute()) # FalseOn Windows, a path needs both a drive and a root to be absolute. /data has a root but no drive. C:data has a drive but no root, so it means "data relative to the current directory on drive C". The POSIX flavor sees C: as just a directory name.
The same logic changes joining. A segment with a drive replaces the whole path. A segment with only a root keeps the drive:
from pathlib import PureWindowsPath
base = PureWindowsPath("C:/a")
print(base / "/b") # C:\b
print(base / "D:/b") # D:\bThis is the Windows version of the pitfall that Path("a") / "/etc" gives /etc.
Converting between flavors
pathlib has no direct converter, because the flavors do not map one to one. Two patterns cover most needs.
Use as_posix() to get a forward-slash string from either flavor. This is how you store paths in a portable format such as JSON, a manifest, or a zip entry name.
from pathlib import PurePosixPath, PureWindowsPath
win = PureWindowsPath(r"C:\Users\ana\file.txt")
text = win.as_posix()
print(text) # C:/Users/ana/file.txt
print(PurePosixPath(text)) # C:/Users/ana/file.txtAfter that conversion, C: is an ordinary first component in the POSIX flavor. Decide whether to strip the drive before you use the path as a location. If you want a relative path, call relative_to on the Windows path first, then use as_posix().
Validating untrusted names on every flavor
A name that is harmless on one system can be dangerous on another. On Linux, ..\..\secret is one odd filename. If the same name is later used on Windows, it climbs out of the target directory. To validate names from an unknown source, test them under both flavors.
from pathlib import PurePosixPath, PureWindowsPath
def is_unsafe(name: str) -> bool:
for flavor in (PurePosixPath, PureWindowsPath):
p = flavor(name)
if p.is_absolute() or p.drive or p.root or ".." in p.parts:
return True
return False
for name in ["docs/readme.txt", "../x", "..\\x", "/etc/passwd", "C:foo", "\\\\srv\\share\\f"]:
print(repr(name), is_unsafe(name))Only the first name prints False. The checks for drive and root catch C:foo, which is_absolute() alone would miss.
Choosing the right class
- Use
Pathwhen you read, write, or list files on the machine running the code. - Use
PurePosixPathfor paths that always use forward slashes, such as URL paths, zip entry names, and container paths. - Use
PureWindowsPathfor paths that come from Windows systems or Windows configuration files. - Use
PurePathwhen you want the local flavor but no file system access, for example in a function that only transforms names.
Common mistakes
- Using
Pathto parse foreign paths. On Linux,Path(r"C:\Users\ana").namereturns the whole string, because the backslashes are not separators there. - Comparing paths of different flavors and expecting a match. They are never equal.
- Calling
exists()orresolve()on a pure path. These raiseAttributeError. - Assuming a path starting with
/is absolute in the Windows flavor. It is not, because it has no drive. - Forgetting that Windows-flavor comparison ignores case, which matters when you deduplicate paths.
Exercise
On a Linux machine, what do PurePosixPath("reports\\2026.csv").parts and PureWindowsPath("reports\\2026.csv").parts return, and why do they differ?
Show answer
The POSIX call returns ('reports\\2026.csv',), one component, because a backslash is an ordinary filename character in the POSIX flavor. The Windows call returns ('reports', '2026.csv'), because the Windows flavor treats both / and \ as separators.
Exercise
Write a function portable_name(text) that takes a Windows path string such as C:\Users\ana\file.txt. It must return the path below the drive as a forward-slash string without a leading slash, here Users/ana/file.txt. Use only pure paths.
Show answer
Build the Windows path, remove the anchor, and convert:
from pathlib import PureWindowsPath
def portablename(text):
p = PureWindowsPath(text)
return p.relativeto(p.anchor).asposix()
print(portablename(r"C:\Users\ana\file.txt")) # Users/ana/file.txt
Calling relative_to(p.anchor) removes the drive and root together, and as_posix() produces forward slashes.