pathlib — 面向对象的文件系统路径

Added in version 3.4.

源代码: Lib/pathlib/


此模块提供表示文件系统路径的类,采用适合不同操作系统的语义。路径类分为 纯路径 ,提供没有 I/O 的纯计算操作,和 具体路径 ,继承自纯路径但还提供 I/O 操作。

Inheritance diagram showing the classes available in pathlib. The most basic class is PurePath, which has three direct subclasses: PurePosixPath, PureWindowsPath, and Path. Further to these four classes, there are two classes that use multiple inheritance: PosixPath subclasses PurePosixPath and Path, and WindowsPath subclasses PureWindowsPath and Path.

若之前从未用过此模块,或仅仅不确定哪个类适合任务, Path 更可能是您需要的。它实例化 具体路径 对于代码所运行的平台。

纯路径在某些特殊情况下很有用;例如:

  1. 若想要在 Unix 机器中操纵 Windows 路径 (反之亦然)。不能实例化 WindowsPath 当运行在 Unix 时,但可以实例化 PureWindowsPath .

  2. 想要确保代码只操纵路径而不实际访问操作系统。在这种情况下,实例化一个纯类可能是有用的,因为它们没有任何操作系统访问操作。

另请参阅

PEP 428 :pathlib 模块 – 面向对象的文件系统路径。

另请参阅

对于低级字符串路径操纵,还可以使用 os.path 模块。

基本用法

导入主类:

>>> from pathlib import Path