Pure paths and Windows vs POSIX

pathlib · Advanced · 10 min

Tools that build remote paths (S3 keys, SSH targets, Windows shares from Linux) need the other OS's rules.

pathlib has two families of classes:

  • Pure paths (PurePath, PurePosixPath, PureWindowsPath) do only string operations: joining, parts, suffixes, matching. They never touch the file system, so they work for any platform's paths on any platform.
  • Concrete paths (Path, PosixPath, WindowsPath) add I/O methods. You can only instantiate the concrete class of your own OS; WindowsPath on Linux raises UnsupportedOperation (3.13).

Use pure paths when the path isn't on the local machine:

  • PurePosixPath("bucket") / "2025" / "a.csv" for object-store keys or paths on a remote Linux server, even when your code runs on Windows.
  • PureWindowsPath(r"C:\Users\ann\file.txt") to parse Windows paths received in data on a Linux server.

Windows rules differ: both \ and / are separators, drives and UNC shares form the anchor (C:\, \\server\share\), comparison is case-insensitive, and p.as_posix() converts to forward slashes.

p.as_uri() turns an absolute path into a file:// URL, and since 3.13 Path.from_uri() parses one back.

Note that pure paths accept any string; they won't tell you a name is invalid on Windows (such as CON or one containing :).

Example

from pathlib import Path, PurePosixPath, PureWindowsPath

w = PureWindowsPath(r"C:\Users\Ann\Docs/report.DOCX")
print(w.parts)        # ('C:\\', 'Users', 'Ann', 'Docs', 'report.DOCX')
print(w.drive, w.suffix)               # C: .DOCX
print(w.as_posix())                    # C:/Users/Ann/Docs/report.DOCX
print(w == PureWindowsPath(r"c:\users\ann\docs\REPORT.docx"))  # True

key = PurePosixPath("exports") / "2025" / "sales.csv"   # e.g. an S3 key
print(str(key))                        # exports/2025/sales.csv

uri = Path("/tmp/a b.txt").as_uri()
print(uri)                             # file:///tmp/a%20b.txt
print(Path.from_uri(uri))              # /tmp/a b.txt

Remember

  • Pure paths do string-only path logic for any OS; concrete paths add I/O
  • Use PurePosixPath for remote or object-store paths regardless of the local OS
  • Windows paths compare case-insensitively and accept both slash styles

Watch out for

  • Using Path (and so local separators) to build S3 keys or remote Linux paths when code may run on Windows.

Check yourself

  1. On Linux, what happens with PureWindowsPath('D:/data') / 'x.txt'?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/pathlib.html#pure-paths