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

3.4 版的新Function。

源代码: Lib/pathlib.py


该模块提供了具有适用于不同 os 的语义的表示文件系统路径的类。路径类分为pure pathsconcrete paths,它们分别提供纯计算操作而没有 I/O,而concrete paths从纯路径继承而来,但也提供 I/O 操作。

../_images/pathlib-inheritance.png

如果您以前从未使用过此模块,或者不确定不确定哪个类适合您的任务,则很可能需要Path。它为运行代码的平台实例化一个concrete path

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

  • 如果要在 Unix 计算机上操作 Windows 路径(反之亦然)。在 Unix 上运行时,不能实例化WindowsPath,但是可以实例化PureWindowsPath

  • 您要确保您的代码仅操纵路径而没有实际访问 os。在这种情况下,实例化纯类之一可能会很有用,因为它们根本没有任何 OS 访问操作。

See also

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

See also

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

Basic use

导入主类:

>>> from pathlib import Path

Listing subdirectories:

>>> p = Path('.')
>>> [x for x in p.iterdir() if x.is_dir()]
[PosixPath('.hg'), PosixPath('docs'), PosixPath('dist'),
 PosixPath('__pycache__'), PosixPath('build')]

在此目录树中列出 Python 源文件:

>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
 PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
 PosixPath('build/lib/pathlib.py')]

在目录树中导航:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

查询路径属性:

>>> q.exists()
True
>>> q.is_dir()
False

打开文件:

>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'

Pure paths

纯路径对象提供了实际上不访问文件系统的路径处理操作。有三种访问这些类的方式,我们也将这些方式称为* flavors *:

>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')
  • pathsegments *的每个元素可以是代表路径段的字符串,实现返回字符串的os.PathLike接口的对象或另一个路径对象:
>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')

当* pathsegments *为空时,假定当前目录为:

>>> PurePath()
PurePosixPath('.')

当给出几个绝对路径时,最后一个被当作锚点(模仿os.path.join()的行为):

>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')

但是,在 Windows 路径中,更改本地根目录不会放弃先前的驱动器设置:

>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')

虚斜线和单点折叠,但双点('..')没有折叠,因为这会改变符号链接中路径的含义:

>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')

(幼稚的方法会使PurePosixPath('foo/../bar')等效于PurePosixPath('bar'),如果foo是到另一个目录的符号链接,这是错误的)

纯路径对象实现os.PathLike接口,从而允许在接受该接口的任何地方使用它们。

在 3.6 版中进行了更改:添加了对os.PathLike界面的支持。

  • 类别 pathlib. PurePosixPath(*路径段)
    • PurePath的子类,此路径包含非 Windows 文件系统路径:
>>> PurePosixPath('/etc')
PurePosixPath('/etc')
  • pathsegments *的指定方式类似于PurePath
  • 类别 pathlib. PureWindowsPath(*路径段)
    • PurePath的子类,此路径表示 Windows 文件系统路径:
>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')
  • pathsegments *的指定方式类似于PurePath

不管运行的系统是什么,都可以实例化所有这些类,因为它们不提供任何执行系统调用的操作。

General properties

路径是不可变且可哈希的。具有相同风味的路径是可比较且可排序的。这些属性遵循该风味的大小写折叠语义:

>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True

不同口味的路径比较不相等,无法排序:

>>> PureWindowsPath('foo') == PurePosixPath('foo')
False
>>> PureWindowsPath('foo') < PurePosixPath('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'PureWindowsPath' and 'PurePosixPath'

Operators

斜杠运算符可帮助创建子路径,类似于os.path.join()

>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')

路径对象可以在接受实现os.PathLike的对象的任何地方使用:

>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'

路径的字符串表示形式是原始文件系统路径本身(本机格式,例如 Windows 下的反斜杠),您可以将其传递给以文件路径为字符串的任何函数:

>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'

类似地,在路径上调用bytes会将原始文件系统路径作为字节对象,由os.fsencode()编码:

>>> bytes(p)
b'/etc'

Note

仅在 Unix 下建议调用bytes。在 Windows 下,unicode 形式是文件系统路径的规范表示。

访问各个部分

要访问路径的各个“部分”(组件),请使用以下属性:

  • PurePath. parts
    • 一个 Tuples,可以访问路径的各个组成部分:
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')

(请注意如何将驱动器和本地根重组为单个部分)

方法和属性

纯路径提供以下方法和属性:

  • PurePath. drive
    • 代表驱动器号或名称的字符串(如果有):
>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
''
>>> PurePosixPath('/etc').drive
''

UNC 共享也被认为是驱动器:

>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'
  • PurePath. root
    • 代表(本地或全局)根的字符串(如果有):
>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
''
>>> PurePosixPath('/etc').root
'/'

UNC 共享始终具有根:

>>> PureWindowsPath('//host/share').root
'\\'
  • PurePath. anchor
    • 驱动器和根目录的串联:
>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'
  • PurePath. parents
    • 提供访问路径的逻辑祖先的不可变序列:
>>> p = PureWindowsPath('c:/foo/bar/setup.py')
>>> p.parents[0]
PureWindowsPath('c:/foo/bar')
>>> p.parents[1]
PureWindowsPath('c:/foo')
>>> p.parents[2]
PureWindowsPath('c:/')
  • PurePath. parent
    • 路径的逻辑父级:
>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')

您不能越过锚点或空路径:

>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')

Note

这是纯粹的词汇操作,因此具有以下行为:

>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')

如果要向上走任意文件系统路径,建议先调用Path.resolve()以便解析符号链接并消除“ ..”组件。

  • PurePath. name
    • 代表finally路径组件的字符串,不包括驱动器和根目录(如果有):
>>> PurePosixPath('my/library/setup.py').name
'setup.py'

不考虑 UNC 驱动器名称:

>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''
  • PurePath. suffix
    • finally组件的文件 extensions(如果有):
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''
  • PurePath. suffixes
    • 路径的文件 extensions 列表:
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
  • PurePath. stem
    • finally路径组件,不带后缀:
>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
  • PurePath. as_posix ( )
    • 返回带有正斜杠(/)的路径的字符串表示形式:
>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
  • PurePath. as_uri ( )
    • 将路径表示为file URI。如果路径不是绝对的,则引发ValueError
>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
  • PurePath. is_absolute ( )
    • 返回路径是否为绝对路径。如果路径既有根又有驱动器(如果允许的话),则视为绝对路径:
>>> PurePosixPath('/a/b').is_absolute()
True
>>> PurePosixPath('a/b').is_absolute()
False

>>> PureWindowsPath('c:/a/b').is_absolute()
True
>>> PureWindowsPath('/a/b').is_absolute()
False
>>> PureWindowsPath('c:').is_absolute()
False
>>> PureWindowsPath('//some/share').is_absolute()
True
  • PurePath. is_reserved ( )
    • 使用PureWindowsPath,如果该路径在 Windows 下被认为是保留的,则返回True,否则返回False。对于PurePosixPath,总是返回False
>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
False

保留路径上的文件系统调用可能会神秘地失败或产生意想不到的影响。

  • PurePath. joinpath(** other *)
    • 调用此方法等效于依次将路径与每个* other *参数组合在一起:
>>> PurePosixPath('/etc').joinpath('passwd')
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
PurePosixPath('/etc/passwd')
>>> PurePosixPath('/etc').joinpath('init.d', 'apache2')
PurePosixPath('/etc/init.d/apache2')
>>> PureWindowsPath('c:').joinpath('/Program Files')
PureWindowsPath('c:/Program Files')
  • PurePath. match(模式)
    • 将此路径与提供的 glob 样式模式匹配。如果匹配成功,则返回True,否则返回False

如果* pattern *是相对的,则路径可以是相对的或绝对的,并且从右侧进行匹配:

>>> PurePath('a/b.py').match('*.py')
True
>>> PurePath('/a/b/c.py').match('b/*.py')
True
>>> PurePath('/a/b/c.py').match('a/*.py')
False

如果* pattern *是绝对的,则路径必须是绝对的,并且整个路径必须匹配:

>>> PurePath('/a.py').match('/*.py')
True
>>> PurePath('a/b.py').match('/*.py')
False

与其他方法一样,区分大小写遵循平台默认值:

>>> PurePosixPath('b.py').match('*.PY')
False
>>> PureWindowsPath('b.py').match('*.PY')
True
  • PurePath. relative_to(** other *)
    • 相对于* other *表示的路径,计算此路径的版本。如果不可能,则引发 ValueError:
>>> p = PurePosixPath('/etc/passwd')
>>> p.relative_to('/')
PurePosixPath('etc/passwd')
>>> p.relative_to('/etc')
PurePosixPath('passwd')
>>> p.relative_to('/usr')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 694, in relative_to
    .format(str(self), str(formatted)))
ValueError: '/etc/passwd' does not start with '/usr'
  • PurePath. with_name(* name *)
    • 返回更改为name的新路径。如果原始路径没有名称,则会引发 ValueError:
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_name('setup.py')
PureWindowsPath('c:/Downloads/setup.py')
>>> p = PureWindowsPath('c:/')
>>> p.with_name('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/antoine/cpython/default/Lib/pathlib.py", line 751, in with_name
    raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty name
  • PurePath. with_suffix(后缀)
    • 返回更改为suffix的新路径。如果原始路径没有后缀,则会附加新的后缀。如果后缀为空字符串,则将删除原始后缀:
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_suffix('.bz2')
PureWindowsPath('c:/Downloads/pathlib.tar.bz2')
>>> p = PureWindowsPath('README')
>>> p.with_suffix('.txt')
PureWindowsPath('README.txt')
>>> p = PureWindowsPath('README.txt')
>>> p.with_suffix('')
PureWindowsPath('README')

Concrete paths

具体路径是纯路径类的子类。除了后者提供的操作外,它们还提供对路径对象进行系统调用的方法。有三种方法可以实例化具体路径:

  • 类别 pathlib. Path(*路径段)
>>> Path('setup.py')
PosixPath('setup.py')
  • pathsegments *的指定方式类似于PurePath
  • 类别 pathlib. PosixPath(*路径段)
    • PathPurePosixPath的子类,该类表示具体的非 Windows 文件系统路径:
>>> PosixPath('/etc')
PosixPath('/etc')
  • pathsegments *的指定方式类似于PurePath
  • 类别 pathlib. WindowsPath(*路径段)
>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')
  • pathsegments *的指定方式类似于PurePath

您只能实例化与您的系统相对应的类风味(允许系统调用不兼容的路径风味可能会导致应用程序中的错误或失败):

>>> import os
>>> os.name
'posix'
>>> Path('setup.py')
PosixPath('setup.py')
>>> PosixPath('setup.py')
PosixPath('setup.py')
>>> WindowsPath('setup.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 798, in __new__
    % (cls.__name__,))
NotImplementedError: cannot instantiate 'WindowsPath' on your system

Methods

除了纯路径方法外,具体路径还提供以下方法。如果系统调用失败(例如,因为路径不存在),那么许多方法都可以引发OSError

在 3.8 版中进行了更改:exists()is_dir()is_file()is_mount()is_symlink()is_block_device()is_char_device()is_fifo()is_socket()现在返回False,而不是为包含在 OS 级别无法表示的字符的路径引发异常。

  • 分类方法 Path. cwd()
    • 返回代表当前目录的新路径对象(由os.getcwd()返回):
>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
  • 分类方法 Path. home()
    • 返回一个表示用户主目录的新路径对象(由os.path.expanduser()使用~构造返回):
>>> Path.home()
PosixPath('/home/antoine')

3.5 版中的新Function。

  • Path. stat ( )
    • 返回包含有关此路径的信息的os.stat_result对象,例如os.stat()。在每次调用此方法时都会查询结果。
>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554
  • Path. chmod(模式)
    • 更改文件模式和权限,例如os.chmod()
>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060
  • Path. exists ( )
    • 路径是否指向现有文件或目录:
>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False

Note

如果路径指向符号链接,则exists()返回符号链接是否指向现有文件或目录。

  • Path. expanduser ( )
>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

3.5 版中的新Function。

  • Path. glob(模式)
    • 在此路径表示的目录中显示给定的相对* pattern *,产生所有匹配的文件(任何类型):
>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]

**”模式表示“此目录和所有子目录(递归)”。换句话说,它启用了递归遍历:

>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]

Note

在大型目录树中使用“ **”模式可能会花费过多时间。

  • Path. group ( )

    • 返回拥有该文件的组的名称。如果在系统数据库中找不到文件的 gid,则引发KeyError
  • Path. is_dir ( )

    • 如果路径指向目录(或指向目录的符号链接),则返回True;如果路径指向另一种文件,则返回False

如果路径不存在或符号链接断开,则也返回False;其他错误(例如权限错误)也会传播。

  • Path. is_file ( )
    • 如果路径指向常规文件(或指向常规文件的符号链接),则返回True;如果路径指向另一种文件,则返回False

如果路径不存在或符号链接断开,则也返回False;其他错误(例如权限错误)也会传播。

  • Path. is_mount ( )
    • 如果路径是* mount point ,则返回True:文件系统中已安装其他文件系统的点。在 POSIX 上,该函数检查 path 的父path/..是否与 path 在不同的设备上,或者path/.. path *指向同一设备上的同一 i 节点-这应该检测安装点适用于所有 Unix 和 POSIX 变体。在 Windows 上未实现。

3.7 版中的新Function。

如果路径不存在,则返回False;其他错误(例如权限错误)也会传播。

  • Path. is_socket ( )
    • 如果路径指向 Unix 套接字(或指向 Unix 套接字的符号链接),则返回True;如果路径指向另一种文件,则返回False

如果路径不存在或符号链接断开,则也返回False;其他错误(例如权限错误)也会传播。

  • Path. is_fifo ( )
    • 如果路径指向 FIFO(或指向 FIFO 的符号链接),则返回True;如果路径指向另一种文件,则返回False

如果路径不存在或符号链接断开,则也返回False;其他错误(例如权限错误)也会传播。

  • Path. is_block_device ( )
    • 如果路径指向块设备(或指向块设备的符号链接),则返回True;如果路径指向另一种文件,则返回False

如果路径不存在或符号链接断开,则也返回False;其他错误(例如权限错误)也会传播。

  • Path. is_char_device ( )
    • 如果路径指向字符设备(或指向字符设备的符号链接),则返回True;如果路径指向另一种文件,则返回False

如果路径不存在或符号链接断开,则也返回False;其他错误(例如权限错误)也会传播。

  • Path. iterdir ( )
    • 当路径指向目录时,产生目录内容的路径对象:
>>> p = Path('docs')
>>> for child in p.iterdir(): child
...
PosixPath('docs/conf.py')
PosixPath('docs/_templates')
PosixPath('docs/make.bat')
PosixPath('docs/index.rst')
PosixPath('docs/_build')
PosixPath('docs/_static')
PosixPath('docs/Makefile')
  • Path. lchmod(模式)

    • 类似于Path.chmod(),但是,如果路径指向符号链接,则符号链接的模式将更改,而不是其目标模式。
  • Path. lstat ( )

    • Path.stat()相似,但是,如果路径指向符号链接,则返回符号链接的信息,而不是其目标信息。
  • Path. mkdir(* mode = 0o777 parents = False exist_ok = False *)

    • 在此给定路径下创建一个新目录。如果给定* mode *,它将与进程的umask值组合以确定文件模式和访问标志。如果路径已经存在,则引发FileExistsError

如果* parents 为 true,则根据需要创建此路径的所有丢失的父级;它们是使用默认权限创建的,而不考虑 mode *(类似于 POSIX mkdir -p命令)。

如果* parents *为 false(默认值),则缺少 parent 的 parent 会引发FileNotFoundError

如果* exist_ok *为 false(默认值),则在目标目录已存在的情况下引发FileExistsError

如果* exist_ok *为 true,则将忽略FileExistsError个异常(与 POSIX mkdir -p命令相同的行为),但前提是最后一个路径组件不是现有的非目录文件。

在版本 3.5 中更改:添加了* exist_ok *参数。

  • Path. open(* mode ='r' buffering = -1 encoding = None errors = None newline = None *)
    • 像内置的open()函数一样,打开路径指向的文件:
>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'
  • Path. owner ( )

    • 返回拥有该文件的用户的名称。如果在系统数据库中找不到文件的 uid,则引发KeyError
  • Path. read_bytes ( )

    • 以字节对象的形式返回指向文件的二进制内容:
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

3.5 版中的新Function。

  • Path. read_text(* encoding = None errors = None *)
    • 以字符串形式返回指向文件的解码内容:
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

该文件被打开,然后关闭。可选参数的含义与open()中的含义相同。

3.5 版中的新Function。

  • Path. rename(* target *)
    • 将此文件或目录重命名为给定的* target ,并返回指向 target 的新 Path 实例。在 Unix 上,如果 target *存在并且是文件,则在用户具有权限的情况下将以静默方式替换它。 * target *可以是字符串或其他路径对象:
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'

在版本 3.8 中更改:添加了返回值,返回新的 Path 实例。

  • Path. replace(* target *)
    • 将此文件或目录重命名为给定的* target ,并返回指向 target 的新 Path 实例。如果 target *指向现有文件或目录,它将被无条件替换。

在版本 3.8 中更改:添加了返回值,返回新的 Path 实例。

  • Path. resolve(* strict = False *)
    • 使路径绝对,解决任何符号链接。返回一个新的路径对象:
>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')

还消除了“ ..”组件(这是唯一的方法):

>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')

如果路径不存在并且* strict True,则引发FileNotFoundError。如果 strict *为False,则将尽可能地解析路径,并且在不检查路径是否存在的情况下附加任何剩余路径。如果沿解析路径遇到无限循环,则会引发RuntimeError

3.6 版中的新Function:* strict *参数(3.6 之前的行为是严格的)。

  • Path. rglob(模式)
    • 这就像在给定的相对* pattern *前面加上“ **/”来调用Path.glob()一样:
>>> sorted(Path().rglob("*.py"))
[PosixPath('build/lib/pathlib.py'),
 PosixPath('docs/conf.py'),
 PosixPath('pathlib.py'),
 PosixPath('setup.py'),
 PosixPath('test_pathlib.py')]
  • Path. rmdir ( )

    • 删除该目录。该目录必须为空。
  • Path. samefile(* other_path *)

如果由于某种原因无法访问任何一个文件,则可以引发OSError

>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
True

3.5 版中的新Function。

  • Path. symlink_to(* target target_is_directory = False *)
    • 将此路径作为指向* target 的符号链接。在 Windows 下,如果链接的目标是目录,则 target_is_directory 必须为 true(默认为False)。在 POSIX 下, target_is_directory *的值将被忽略。
>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')
>>> p.stat().st_size
956
>>> p.lstat().st_size
8

Note

参数(链接,目标)的 Sequences 与os.symlink()的 Sequences 相反。

  • Path. touch(* mode = 0o666 exist_ok = True *)

    • 在此给定路径下创建一个文件。如果给定* mode ,它将与进程的umask值组合以确定文件模式和访问标志。如果文件已经存在,则如果 exist_ok *为 true(并且其修改时间已更新为当前时间),则函数成功执行,否则引发FileExistsError
  • Path. unlink(* missing_ok = False *)

    • 删除此文件或符号链接。如果路径指向目录,请改用Path.rmdir()

如果* missing_ok *为 false(默认值),则在路径不存在时引发FileNotFoundError

如果* missing_ok *为 true,则将忽略FileNotFoundError个异常(与 POSIX rm -f命令的行为相同)。

在 3.8 版中进行了更改:添加了* missing_ok *参数。

  • Path. link_to(* target *)
    • 创建一个指向名为* target *的路径的硬链接。

在 3.8 版中进行了更改。

  • Path. write_bytes(* data *)
    • 打开以字节模式指向的文件,向其中写入* data *,然后关闭文件:
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

具有相同名称的现有文件将被覆盖。

3.5 版中的新Function。

  • Path. write_text(* data encoding = None errors = None *)
    • 打开以文本模式指向的文件,向其中写入* data *,然后关闭文件:
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

具有相同名称的现有文件将被覆盖。可选参数的含义与open()中的含义相同。

3.5 版中的新Function。

对应于 os 模块中的工具

下面的表格将各种os函数 Map 到它们对应的PurePath/Path等价物。

Note

尽管os.path.relpath()PurePath.relative_to()有一些重叠的用例,但它们的语义差异足以确保不认为它们等效。

os 和 os.pathpathlib
os.path.abspath()Path.resolve()
os.chmod()Path.chmod()
os.mkdir()Path.mkdir()
os.rename()Path.rename()
os.replace()Path.replace()
os.rmdir()Path.rmdir()
os.remove(), os.unlink()Path.unlink()
os.getcwd()Path.cwd()
os.path.exists()Path.exists()
os.path.expanduser()Path.expanduser()Path.home()
os.path.isdir()Path.is_dir()
os.path.isfile()Path.is_file()
os.path.islink()Path.is_symlink()
os.stat()Path.stat(), Path.owner(), Path.group()
os.path.isabs()PurePath.is_absolute()
os.path.join()PurePath.joinpath()
os.path.basename()PurePath.name
os.path.dirname()PurePath.parent
os.path.samefile()Path.samefile()
os.path.splitext()PurePath.suffix