TATECHATLAS
◎ 简体中文
编程 / 建议

PurePath 与 Path:当路径数学不是文件系统真相时

使用 PurePath 系列类进行可移植的、无 I/O 的路径操作,使用 Path/PosixPath/WindowsPath 进行文件系统相关的工作。不要将词法规范化视为目标存在、通过符号链接解析或包含的证明。

本文内容

在仅需要路径结构时,选择 PurePath、PurePosixPath 或 PureWindowsPath:连接、拆分、比较或操作 Windows 风格的路径在 Unix 上。在需要真实文件系统行为时,选择 Path、PosixPath 或 WindowsPath。PurePath 会折叠多余的斜线和单点,但会保留 '..' 和前导双斜线,因为对它们进行天真的解析会改变符号链接和 UNC 路径的含义。具体路径类只能在当前平台风格上实例化,并且它们的系统调用方法在底层调用失败时可能会引发 OSError。在信任路径用于存在、包含、符号链接目标或安全性之前,根据需要调用 resolve() 或文件系统检查,如 exists()、is_file()、is_dir() 或 is_symlink()。

选择适合工作的正确路径类

pathlib 在 Python 3.4 中添加,将路径类分为纯路径和具体路径。纯路径提供无 I/O 的计算操作;具体路径继承自纯路径并添加系统调用操作。如果你不确定,Path 通常是正确的默认选择,因为它会实例化运行代码的平台的具体路径。

在必须操作外来风格(如 Unix 机器上的 Windows 路径)或仅操作路径字符串而不触及操作系统的情况下,使用 PurePosixPath 或 PureWindowsPath。你不能在 Unix 上实例化 WindowsPath,但可以实例化 PureWindowsPath。纯路径还实现了 os.PathLike,因此可以传递到接受该接口的任何地方。

在上述示例中,PureWindowsPath 解析 Windows 风格的路径并提取父、干、后缀和部分,而无需任何系统调用。这在脚本在 Linux、macOS 或 Windows 上运行时都能相同地工作。Path('setup.py') 则实例化与主机操作系统匹配的具体类,因此 type(q) 在 Unix 上打印 PosixPath,在 Windows 上打印 WindowsPath。

from pathlib import PurePath, PurePosixPath, PureWindowsPath, Path

# PureWindowsPath works on any OS for structural manipulation
p = PureWindowsPath(r'C:\Users\alice\Documents\report.pdf')
print(p.parent)          # C:\Users\alice\Documents
print(p.stem)            # report
print(p.suffix)          # .pdf
print(p.parts)           # ('C:\\', 'Users', 'alice', 'Documents', 'report.pdf')

# Path instantiates the concrete class for the running platform
q = Path('setup.py')
print(type(q))           # <class 'pathlib.PosixPath'> on Linux, <class 'pathlib.WindowsPath'> on Windows

理解为什么 '..' 不会被折叠

PurePath 会折叠重复的斜线和单点,但它故意保留双点和前导双斜线完好无损。这不是一个错误;天真的折叠会将 'foo/../bar' 转换为 'bar',这在 foo 是指向另一个目录的符号链接时是错误的。

对前导双斜线的相同谨慎也适用,因为它们在 UNC 或平台特定的路径语义中可能有意义。因此,词法规范化只是一个结构操作,而不是通过文件系统解析路径。

示例演示了四个规则和具体输入。PurePosixPath('foo//bar') 折叠为 'foo/bar',PurePosixPath('foo/./bar') 折叠为 'foo/bar'。但 PurePosixPath('foo/../bar') 保持为 'foo/../bar',PurePosixPath('//foo/bar') 保留前导双斜线。Windows 风格遵循相同的逻辑:反斜线分隔的双点保留,UNC 前缀如 servershare 也被保留。

from pathlib import PurePosixPath, PureWindowsPath

# Spurious slashes and single dots are collapsed
print(PurePosixPath('foo//bar'))       # foo/bar
print(PurePosixPath('foo/./bar'))      # foo/bar

# Double dots are NOT collapsed
print(PurePosixPath('foo/../bar'))     # foo/../bar

# Leading double slashes are NOT collapsed
print(PurePosixPath('//foo/bar'))      # //foo/bar

# Same rules apply to Windows flavour
print(PureWindowsPath(r'foo\..\bar'))  # foo\..\bar
print(PureWindowsPath(r'\\server\share'))  # \\server\share

仅在需要文件系统真相时使用具体路径

具体路径是纯路径的子类,并添加了执行系统调用的方法。Path 实例化当前平台的具体路径,即 PosixPath 或 WindowsPath。PosixPath 和 WindowsPath 是具体子类,但只有与运行系统匹配的风格才能实例化以进行系统调用;自 Python 3.13 起,不匹配的风格会引发 UnsupportedOperation 而不是 NotImplementedError。由于 UnsupportedOperation 继承自 NotImplementedError,现有代码仍然可以处理较新的错误,而特别捕获 UnsupportedOperation 的代码可以区分这两种情况。

一些具体方法在系统调用失败时可能会引发 OSError,例如因为路径不存在。这是文件系统相关工作的特性,而不是使用 PurePath 进行存在检查的原因。

在需要 iterdir()、glob()、open()、exists()、is_file()、is_dir()、stat()、resolve() 或类似操作时,使用 Path。在仅需要路径结构且希望避免意外 I/O 时,使用 PurePath。

示例创建了一个临时目录树,然后使用 Path 方法查询实际文件系统。exists()、is_dir() 和 is_file() 返回基于实际目录条目的布尔值。不存在的路径返回 False 而不是引发错误。从相同字符串构造的 PurePosixPath 可以提取 .name 但没有 exists() 方法,确认纯路径在结构上受到限制。

from pathlib import Path, PurePosixPath
import tempfile, os

# Create a temporary directory with a known structure
with tempfile.TemporaryDirectory() as tmpdir:
    base = Path(tmpdir)
    (base / 'sub').mkdir()
    (base / 'sub' / 'file.txt').write_text('hello')

    # Concrete operations query the real filesystem
    print((base / 'sub').exists())        # True
    print((base / 'sub').is_dir())        # True
    print((base / 'sub' / 'file.txt').is_file())  # True
    print((base / 'missing').exists())    # False

    # Pure path cannot answer these questions
    pp = PurePosixPath(base / 'sub' / 'file.txt')
    print(pp.name)                        # file.txt
    # pp.exists() would raise AttributeError

在信任路径结果之前应用限制

纯路径不执行 I/O 并不能证明路径存在、是目录、是符号链接或通过符号链接解析。如 PurePosixPath('foo/../bar') 这样的词法结果不是关于文件系统的承诺。

具体 Path 结果也不是无条件的证明:方法可以引发 OSError,resolve() 是文件系统感知的步骤,它会跟随符号链接。对于包含或安全性决策,首先解析,然后比较或检查解析后的路径。

路径操作不应被视为显式检查的替代品。如果决策取决于存在、目标身份或包含,请在操作之前使用 exists()、is_file()、is_dir()、is_symlink()、resolve() 或等效的文件系统检查进行验证。

示例创建了一个符号链接 'link' 指向 'real_dir'。从词法上讲,PurePosixPath 将 'link/sub' 视为 base 目录的子目录。在 resolve() 之后,路径变成了实际目录后面的 'sub',揭示了真正的目标。请注意,解析后的路径可能与 tempfile.TemporaryDirectory() 返回的 tmpdir 字符串不同,因为 resolve() 会展开路径中的所有符号链接;例如,在 macOS 上,/var 是指向 /private/var 的符号链接,因此解析后的输出显示 /private/var/folders/... 而不是 /var/folders/...。然后 relative_to() 检查确认了对解析目录的包含。没有 resolve(),符号链接可能会将访问重定向到预期子树之外,使词法检查在授权决策中不安全。

from pathlib import Path, PurePosixPath
import tempfile, os

with tempfile.TemporaryDirectory() as tmpdir:
    base = Path(tmpdir)
    (base / 'real_dir').mkdir()
    (base / 'link').symlink_to(base / 'real_dir')

    # Lexical containment says 'link/sub' is under base
    lexical = PurePosixPath(base / 'link' / 'sub')
    print(lexical.parts)  # ('/', ..., 'link', 'sub')

    # resolve() follows the symlink to the actual target
    resolved = (base / 'link' / 'sub').resolve()
    # The resolved path reflects the platform's real temp directory.
    # On macOS, /var is a symlink to /private/var, so resolve() may
    # return /private/var/folders/.../real_dir/sub rather than the
    # tmpdir string shown by tempfile.TemporaryDirectory().
    print(resolved)       # <resolved temp dir>/real_dir/sub

    # Containment check after resolve
    target = base / 'real_dir'
    try:
        resolved.relative_to(target)
        print('inside real_dir')
    except ValueError:
        print('outside real_dir')

适用条件

  • 任务仅是结构化路径操作,还是需要真实的文件系统行为?
  • 路径将在与运行代码的平台不同的平台上使用吗?
  • 路径包含 '..'、前导双斜线或符号链接敏感组件吗?
  • 决策是否基于存在、目标身份、包含或安全性,而不是字符串形状?
  • 你是否愿意在采取行动之前调用 resolve() 或文件系统检查?

这不是对每个路径操作都安全的保证,也不是 resolve() 总是足够的保证;resolve() 会跟随符号链接,仍然可能失败或具有平台依赖性。PurePath 仍然有助于可移植性和结构,但它不是在每种情况下替换 os.path 的替代品,并且必须不被用作文件系统真相的证明。

参考来源

  1. Python: json ↗
  2. Python: pathlib ↗
返回顶部 ↑