pathlib
— Object-oriented filesystem paths面向对象的文件系统路径¶
New in version 3.4.版本3.4中新增。
Source code: Lib/pathlib.py
This module offers classes representing filesystem paths with semantics appropriate for different operating systems. 该模块提供了表示文件系统路径的类,这些类具有适合不同操作系统的语义。Path classes are divided between pure paths, which provide purely computational operations without I/O, and concrete paths, which inherit from pure paths but also provide I/O operations.路径类分为纯路径和具体路径,前者提供无需I/O的纯计算操作,后者继承自纯路径,但也提供I/O操作。

If you’ve never used this module before or just aren’t sure which class is right for your task, 如果您以前从未使用过此模块,或者只是不确定哪个类适合您的任务,那么Path
is most likely what you need. Path
很可能就是您所需要的。It instantiates a concrete path for the platform the code is running on.它为运行代码的平台实例化了一个具体路径。
Pure paths are useful in some special cases; for example:纯路径在某些特殊情况下很有用;例如:
If you want to manipulate Windows paths on a Unix machine (or vice versa).如果要在Unix计算机上操作Windows路径(反之亦然)。You cannot instantiate a在Unix上运行时,不能实例化WindowsPath
when running on Unix, but you can instantiatePureWindowsPath
.WindowsPath
,但可以实例化PureWindowsPath
。You want to make sure that your code only manipulates paths without actually accessing the OS.您希望确保代码只处理路径,而不实际访问操作系统。In this case, instantiating one of the pure classes may be useful since those simply don’t have any OS-accessing operations.在这种情况下,实例化其中一个纯类可能很有用,因为这些纯类没有任何操作系统访问操作。
See also
PEP 428: The pathlib module – object-oriented filesystem paths.:pathlib模块-面向对象的文件系统路径。
See also
For low-level path manipulation on strings, you can also use the 对于字符串上的低级路径操作,还可以使用os.path
module.os.path
模块。
Basic use基本用途¶
Importing the main class:导入主类:
>>> 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')]
Listing Python source files in this directory tree:在此目录树中列出Python源文件:
>>> list(p.glob('**/*.py'))
[PosixPath('test_pathlib.py'), PosixPath('setup.py'),
PosixPath('pathlib.py'), PosixPath('docs/conf.py'),
PosixPath('build/lib/pathlib.py')]
Navigating inside a directory tree:在目录树中导航:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
Querying path properties:正在查询路径属性:
>>> q.exists()
True
>>> q.is_dir()
False
Opening a file:打开文件:
>>> with q.open() as f: f.readline()
...
'#!/bin/bash\n'
Pure paths纯路径¶
Pure path objects provide path-handling operations which don’t actually access a filesystem. 纯路径对象提供的路径处理操作实际上并不访问文件系统。There are three ways to access these classes, which we also call flavours:有三种方法可以访问这些类,我们也称之为flavours:
-
class
pathlib.
PurePath
(*pathsegments)¶ A generic class that represents the system’s path flavour (instantiating it creates either a表示系统路径风格的泛型类(实例化它会创建PurePosixPath
or aPureWindowsPath
):PurePosixPath
或PureWindowsPath
):>>> PurePath('setup.py') # Running on a Unix machine
PurePosixPath('setup.py')Each element of pathsegments can be either a string representing a path segment, an object implementing thepathsegments的每个元素可以是表示路径段的字符串、实现返回字符串的os.PathLike
interface which returns a string, or another path object:os.PathLike
接口的对象或另一个路径对象:>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')When pathsegments is empty, the current directory is assumed:pathsegments为空时,假定当前目录为:>>> PurePath()
PurePosixPath('.')When several absolute paths are given, the last is taken as an anchor (mimicking当给定多条绝对路径时,最后一条路径将作为锚点(模仿os.path.join()
’s behaviour):os.path.join()
的行为):>>> PurePath('/etc', '/usr', 'lib64')
PurePosixPath('/usr/lib64')
>>> PureWindowsPath('c:/Windows', 'd:bar')
PureWindowsPath('d:bar')However, in a Windows path, changing the local root doesn’t discard the previous drive setting:但是,在Windows路径中,更改本地根目录不会放弃以前的驱动器设置:>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')Spurious slashes and single dots are collapsed, but double dots (伪斜杠和单点会折叠,但双点('..'
) are not, since this would change the meaning of a path in the face of symbolic links:'..'
)不会折叠,因为这会改变符号链接中路径的含义:>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/./bar')
PurePosixPath('foo/bar')
>>> PurePath('foo/../bar')
PurePosixPath('foo/../bar')(a naïve approach would make(原生方法会使PurePosixPath('foo/../bar')
equivalent toPurePosixPath('bar')
, which is wrong iffoo
is a symbolic link to another directory)PurePosixPath('foo/../bar')
等效于PurePosixPath('bar')
,如果foo
是指向另一个目录的符号链接,这是错误的)Pure path objects implement the纯路径对象实现os.PathLike
interface, allowing them to be used anywhere the interface is accepted.os.PathLike
接口,允许在接受接口的任何地方使用它们。Changed in version 3.6:版本3.6中更改:Added support for the增加了对os.PathLike
interface.os.PathLike
接口的支持。
-
class
pathlib.
PurePosixPath
(*pathsegments)¶ A subclass of作为PurePath
, this path flavour represents non-Windows filesystem paths:PurePath
的子类,此路径风格表示非Windows文件系统路径:>>> PurePosixPath('/etc')
PurePosixPath('/etc')pathsegments
is specified similarly to的指定方式与PurePath
.PurePath
类似。
-
class
pathlib.
PureWindowsPath
(*pathsegments)¶ A subclass of作为PurePath
, this path flavour represents Windows filesystem paths:PurePath
的子类,此路径风格表示Windows文件系统路径:>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')pathsegments
is specified similarly to的指定方式与PurePath
.PurePath
类似。
Regardless of the system you’re running on, you can instantiate all of these classes, since they don’t provide any operation that does system calls.无论您在哪个系统上运行,都可以实例化所有这些类,因为它们不提供任何执行系统调用的操作。
General properties一般属性¶
Paths are immutable and hashable. 路径是不可变和可散列的。Paths of a same flavour are comparable and orderable. 相同风味的路径具有可比性和可排序性。These properties respect the flavour’s case-folding semantics:这些属性尊重风味的大小写折叠语义:
>>> PurePosixPath('foo') == PurePosixPath('FOO')
False
>>> PureWindowsPath('foo') == PureWindowsPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True
>>> PureWindowsPath('C:') < PureWindowsPath('d:')
True
Paths of a different flavour compare unequal and cannot be ordered:不同味道的路径比较不相等,无法排序:
>>> 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运算符¶
The slash operator helps create child paths, similarly to 斜杠运算符帮助创建子路径,类似于os.path.join()
: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')
A path object can be used anywhere an object implementing 路径对象可以在任何接受实现os.PathLike
is accepted:os.PathLike
的对象的地方使用:
>>> import os
>>> p = PurePath('/etc')
>>> os.fspath(p)
'/etc'
The string representation of a path is the raw filesystem path itself (in native form, e.g. with backslashes under Windows), which you can pass to any function taking a file path as a string:路径的字符串表示是原始文件系统路径本身(以本机形式,例如在Windows下使用反斜杠),您可以将其传递给任何将文件路径作为字符串的函数:
>>> p = PurePath('/etc')
>>> str(p)
'/etc'
>>> p = PureWindowsPath('c:/Program Files')
>>> str(p)
'c:\\Program Files'
Similarly, calling 类似地,在路径上调用bytes
on a path gives the raw filesystem path as a bytes object, as encoded by os.fsencode()
:bytes
会将原始文件系统路径作为字节对象,由os.fsencode()
编码:
>>> bytes(p)
b'/etc'
Accessing individual parts访问单个零件¶
To access the individual “parts” (components) of a path, use the following property:要访问路径的各个“部分”(组件),请使用以下属性:
-
PurePath.
parts
¶ A tuple giving access to the path’s various components:一个元组,用于访问路径的各个组件:>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')
>>> p = PureWindowsPath('c:/Program Files/PSF')
>>> p.parts
('c:\\', 'Program Files', 'PSF')(note how the drive and local root are regrouped in a single part)(请注意驱动器和本地根目录是如何在单个部分中重新组合的)
Methods and properties方法和属性¶
Pure paths provide the following methods and properties:纯路径提供以下方法和属性:
-
PurePath.
drive
¶ A string representing the drive letter or name, if any:表示驱动器号或名称的字符串(如果有):>>> PureWindowsPath('c:/Program Files/').drive
'c:'
>>> PureWindowsPath('/Program Files/').drive
''
>>> PurePosixPath('/etc').drive
''UNC shares are also considered drives:UNC共享也被视为驱动器:>>> PureWindowsPath('//host/share/foo.txt').drive
'\\\\host\\share'
-
PurePath.
root
¶ A string representing the (local or global) root, if any:表示(本地或全局)根的字符串(如果有):>>> PureWindowsPath('c:/Program Files/').root
'\\'
>>> PureWindowsPath('c:Program Files/').root
''
>>> PurePosixPath('/etc').root
'/'UNC shares always have a root:UNC共享始终具有根:>>> PureWindowsPath('//host/share').root
'\\'
-
PurePath.
anchor
¶ The concatenation of the drive and root:驱动器和根目录的串联:>>> PureWindowsPath('c:/Program Files/').anchor
'c:\\'
>>> PureWindowsPath('c:Program Files/').anchor
'c:'
>>> PurePosixPath('/etc').anchor
'/'
>>> PureWindowsPath('//host/share').anchor
'\\\\host\\share\\'
-
PurePath.
parents
¶ An immutable sequence providing access to the logical ancestors of the path:提供对路径的逻辑祖先的访问的不可变序列:>>> 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
¶ The logical parent of the path:路径的逻辑父级:>>> p = PurePosixPath('/a/b/c/d')
>>> p.parent
PurePosixPath('/a/b/c')You cannot go past an anchor, or empty path:您不能越过锚点或空路径:>>> p = PurePosixPath('/')
>>> p.parent
PurePosixPath('/')
>>> p = PurePosixPath('.')
>>> p.parent
PurePosixPath('.')Note
This is a purely lexical operation, hence the following behaviour:这是一个纯粹的词法操作,因此有以下行为:>>> p = PurePosixPath('foo/..')
>>> p.parent
PurePosixPath('foo')If you want to walk an arbitrary filesystem path upwards, it is recommended to first call如果要向上遍历任意文件系统路径,建议首先调用Path.resolve()
so as to resolve symlinks and eliminate “..” components.Path.resolve()
,以便解析符号链接并消除““..”组件。
-
PurePath.
name
¶ A string representing the final path component, excluding the drive and root, if any:表示最终路径组件的字符串,不包括驱动器和根(如果有):>>> PurePosixPath('my/library/setup.py').name
'setup.py'UNC drive names are not considered:不考虑UNC驱动器名称:>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''
-
PurePath.
suffix
¶ The file extension of the final component, if any:最终组件的文件扩展名(如果有):>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''
-
PurePath.
suffixes
¶ A list of the path’s file extensions:路径的文件扩展名列表:>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]
-
PurePath.
stem
¶ The final path component, without its suffix:最终路径组件,不带后缀:>>> PurePosixPath('my/library.tar.gz').stem
'library.tar'
>>> PurePosixPath('my/library.tar').stem
'library'
>>> PurePosixPath('my/library').stem
'library'
-
PurePath.
as_posix
()¶ Return a string representation of the path with forward slashes (返回带有正斜杠(/
):/
)的路径的字符串表示形式:>>> p = PureWindowsPath('c:\\windows')
>>> str(p)
'c:\\windows'
>>> p.as_posix()
'c:/windows'
-
PurePath.
as_uri
()¶ Represent the path as a将路径表示为file
URI.file
URI。ValueError
is raised if the path isn’t absolute.如果路径不是绝对路径,则引发。>>> p = PurePosixPath('/etc/passwd')
>>> p.as_uri()
'file:///etc/passwd'
>>> p = PureWindowsPath('c:/Windows')
>>> p.as_uri()
'file:///c:/Windows'
-
PurePath.
is_absolute
()¶ Return whether the path is absolute or not.返回路径是否为绝对路径。A path is considered absolute if it has both a root and (if the flavour allows) a drive:如果路径同时具有根和(如果味道允许)驱动器,则该路径被视为绝对路径:>>> 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_relative_to
(*other)¶ Return whether or not this path is relative to the other path.返回此路径是否相对于other路径。>>> p = PurePath('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
FalseNew in version 3.9.版本3.9中新增。
-
PurePath.
is_reserved
()¶ With对于PureWindowsPath
, returnTrue
if the path is considered reserved under Windows,False
otherwise.PureWindowsPath
,如果路径在Windows下被认为是保留的,则返回True
,否则返回False
。With对于PurePosixPath
,False
is always returned.PurePosixPath
,总是返回False
。>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
FalseFile system calls on reserved paths can fail mysteriously or have unintended effects.保留路径上的文件系统调用可能会神秘失败或产生意外影响。
-
PurePath.
joinpath
(*other)¶ Calling this method is equivalent to combining the path with each of the other arguments in turn:调用此方法相当于依次将路径与每个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
(pattern)¶ Match this path against the provided glob-style pattern.将此路径与提供的全局样式模式相匹配。Return如果匹配成功,则返回True
if matching is successful,False
otherwise.True
,否则返回False
。If pattern is relative, the path can be either relative or absolute, and matching is done from the right:如果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')
FalseIf pattern is absolute, the path must be absolute, and the whole path must match:如果pattern是绝对的,则路径必须是绝对的,并且整个路径必须匹配:>>> PurePath('/a.py').match('/*.py')
True
>>> PurePath('a/b.py').match('/*.py')
FalseAs with other methods, case-sensitivity follows platform defaults:与其他方法一样,区分大小写遵循平台默认值:>>> PurePosixPath('b.py').match('*.PY')
False
>>> PureWindowsPath('b.py').match('*.PY')
True
-
PurePath.
relative_to
(*other)¶ Compute a version of this path relative to the path represented by other.计算此路径相对于other表示的路径的版本。If it’s impossible, ValueError is raised:如果不可能,则会引发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' is not in the subpath of '/usr' OR one path is relative and the other absolute.NOTE: This function is part of注意:此函数是PurePath
and works with strings.PurePath
的一部分,可用于字符串。It does not check or access the underlying file structure.它不检查或访问底层文件结构。
-
PurePath.
with_name
(name)¶ Return a new path with the返回name
changed.name
已更改的新路径。If the original path doesn’t have a name, ValueError is raised:如果原始路径没有名称,则会引发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_stem
(stem)¶ Return a new path with the返回更改了stem
changed.stem
的新路径。If the original path doesn’t have a name, ValueError is raised:如果原始路径没有名称,则会引发ValueError:>>> p = PureWindowsPath('c:/Downloads/draft.txt')
>>> p.with_stem('final')
PureWindowsPath('c:/Downloads/final.txt')
>>> p = PureWindowsPath('c:/Downloads/pathlib.tar.gz')
>>> p.with_stem('lib')
PureWindowsPath('c:/Downloads/lib.gz')
>>> p = PureWindowsPath('c:/')
>>> p.with_stem('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/antoine/cpython/default/Lib/pathlib.py", line 861, in with_stem
return self.with_name(stem + self.suffix)
File "/home/antoine/cpython/default/Lib/pathlib.py", line 851, in with_name
raise ValueError("%r has an empty name" % (self,))
ValueError: PureWindowsPath('c:/') has an empty nameNew in version 3.9.版本3.9中新增。
-
PurePath.
with_suffix
(suffix)¶ Return a new path with the返回suffix
changed.suffix
已更改的新路径。If the original path doesn’t have a suffix, the new suffix is appended instead.如果原始路径没有后缀,则会附加新的后缀。If the suffix is an empty string, the original suffix is removed:如果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具体路径¶
Concrete paths are subclasses of the pure path classes. 具体路径是纯路径类的子类。In addition to operations provided by the latter, they also provide methods to do system calls on path objects. 除了后者提供的操作之外,它们还提供了对路径对象进行系统调用的方法。There are three ways to instantiate concrete paths:实例化具体路径有三种方法:
-
class
pathlib.
Path
(*pathsegments)¶ A subclass of作为PurePath
, this class represents concrete paths of the system’s path flavour (instantiating it creates either aPosixPath
or aWindowsPath
):PurePath
的一个子类,该类表示系统路径风格的具体路径(实例化它会创建PosixPath
或WindowsPath
):>>> Path('setup.py')
PosixPath('setup.py')pathsegments
is specified similarly to的指定方式与PurePath
.PurePath
类似。
-
class
pathlib.
PosixPath
(*pathsegments)¶ A subclass of作为Path
andPurePosixPath
, this class represents concrete non-Windows filesystem paths:Path
和PurePosixPath
的子类,此类表示具体的非Windows文件系统路径:>>> PosixPath('/etc')
PosixPath('/etc')pathsegments is specified similarly topathsegments的指定方式与PurePath
.PurePath
类似。
-
class
pathlib.
WindowsPath
(*pathsegments)¶ A subclass of作为Path
andPureWindowsPath
, this class represents concrete Windows filesystem paths:Path
和PureWindowsPath
的子类,此类表示具体的Windows文件系统路径:>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')pathsegments
is specified similarly to的指定方式与PurePath
.PurePath
类似。
You can only instantiate the class flavour that corresponds to your system (allowing system calls on non-compatible path flavours could lead to bugs or failures in your application):您只能实例化与您的系统相对应的类风格(允许对不兼容的路径风格进行系统调用可能会导致应用程序中出现错误或失败):
>>> 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方法¶
Concrete paths provide the following methods in addition to pure paths methods. 除了纯路径方法之外,具体路径还提供以下方法。Many of these methods can raise an 如果系统调用失败(例如,因为路径不存在),其中许多方法都会引发OSError
if a system call fails (for example because the path doesn’t exist).OSError
。
Changed in version 3.8:版本3.8中更改: exists()
, is_dir()
, is_file()
, is_mount()
, is_symlink()
, is_block_device()
, is_char_device()
, is_fifo()
, is_socket()
now return False
instead of raising an exception for paths that contain characters unrepresentable at the OS level.exists()
、is_dir()
、is_file()
、is_mount()
、is_symlink()
、is_block_device()
、is_char_device()
、is_fifo()
、is_socket()
现在返回False
,而不是对包含操作系统级不可表示的字符的路径引发异常。
-
classmethod
Path.
cwd
()¶ Return a new path object representing the current directory (as returned by返回表示当前目录的新路径对象(由os.getcwd()
):os.getcwd()
返回):>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
-
classmethod
Path.
home
()¶ Return a new path object representing the user’s home directory (as returned by返回表示用户主目录的新路径对象(由os.path.expanduser()
with~
construct).os.path.expanduser()
和~
构造返回)。If the home directory can’t be resolved,如果无法解析主目录,将引发RuntimeError
is raised.RuntimeError
。>>> Path.home()
PosixPath('/home/antoine')New in version 3.5.版本3.5中新增。
-
Path.
stat
(*, follow_symlinks=True)¶ Return a返回一个os.stat_result
object containing information about this path, likeos.stat()
.os.stat_result
对象,该对象包含有关此路径的信息,如os.stat()
。The result is looked up at each call to this method.每次调用此方法时都会查看结果。This method normally follows symlinks; to stat a symlink add the argument此方法通常遵循符号链接;要统计符号链接,请添加参数follow_symlinks=False
, or uselstat()
.follow_symlinks=False
,或使用lstat()
。>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554Changed in version 3.10:版本3.10中更改:The follow_symlinks parameter was added.添加了follow_symlinks参数。
-
Path.
chmod
(mode, *, follow_symlinks=True)¶ Change the file mode and permissions, like更改文件模式和权限,如os.chmod()
.os.chmod()
。This method normally follows symlinks.此方法通常遵循符号链接。Some Unix flavours support changing permissions on the symlink itself; on these platforms you may add the argument一些Unix风格支持更改符号链接本身的权限;在这些平台上,可以添加参数follow_symlinks=False
, or uselchmod()
.follow_symlinks=False
,或使用lchmod()
。>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060Changed in version 3.10:版本3.10中更改:The follow_symlinks parameter was added.添加了follow_symlinks参数。
-
Path.
exists
()¶ Whether the path points to an existing file or directory:路径是否指向现有文件或目录:>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False
-
Path.
expanduser
()¶ Return a new path with expanded返回一个包含扩展~
and~user
constructs, as returned byos.path.expanduser()
.~
和~ser
构造的新路径,如os.path.expanduser()
返回的。If a home directory can’t be resolved,如果无法解析主目录,则会引发RuntimeError
is raised.RuntimeError
。>>> p = PosixPath('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')New in version 3.5.版本3.5中新增。
-
Path.
glob
(pattern)¶ Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind):Glob此路径表示的目录中的给定相对pattern,生成所有匹配文件(任何类型):>>> sorted(Path('.').glob('*.py'))
[PosixPath('pathlib.py'), PosixPath('setup.py'), PosixPath('test_pathlib.py')]
>>> sorted(Path('.').glob('*/*.py'))
[PosixPath('docs/conf.py')]Patterns are the same as for模式与fnmatch
, with the addition of “**
” which means “this directory and all subdirectories, recursively”.fnmatch
的模式相同,只是添加了“**
”,这表示“此目录和所有子目录,递归地”。In other words, it enables recursive globbing:换句话说,它支持递归全局搜索:>>> sorted(Path('.').glob('**/*.py'))
[PosixPath('build/lib/pathlib.py'),
PosixPath('docs/conf.py'),
PosixPath('pathlib.py'),
PosixPath('setup.py'),
PosixPath('test_pathlib.py')]Note
Using the “在大型目录树中使用“**
” pattern in large directory trees may consume an inordinate amount of time.**
”模式可能会耗费大量时间。Raises an auditing event引发具有参数pathlib.Path.glob
with argumentsself
,pattern
.self
、pattern
的审核事件pathlib.Path.glob
。
-
Path.
group
()¶ Return the name of the group owning the file.返回拥有该文件的组的名称。如果在系统数据库中找不到文件的gid,则会引发KeyError
is raised if the file’s gid isn’t found in the system database.KeyError
。
-
Path.
is_dir
()¶ Return如果路径指向目录(或指向目录的符号链接),则返回True
if the path points to a directory (or a symbolic link pointing to a directory),False
if it points to another kind of file.True
;如果路径指向其他类型的文件,则返回False
。如果路径不存在或是断开的符号链接,也会返回False
is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
is_file
()¶ Return如果路径指向常规文件(或指向常规文件的符号链接),则返回True
if the path points to a regular file (or a symbolic link pointing to a regular file),False
if it points to another kind of file.True
;如果路径指向其他类型的文件,则返回False
。如果路径不存在或是断开的符号链接,也会返回False
is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
is_mount
()¶ Return如果路径是装载点,则返回True
if the path is a mount point: a point in a file system where a different file system has been mounted.True
:文件系统中已装载不同文件系统的点。On POSIX, the function checks whether path’s parent,在POSIX上,该函数检查path的父级path/..
, is on a different device than path, or whetherpath/..
and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants.path/..
,与path位于不同的设备上,或者path/..
和path是否指向同一设备上的同一i节点-这应该检测所有Unix和POSIX变体的装入点。Not implemented on Windows.未在Windows上实现。New in version 3.7.版本3.7中新增。
-
Path.
is_symlink
()¶ Return如果路径指向符号链接,则返回True
if the path points to a symbolic link,False
otherwise.True
,否则返回False
。如果路径不存在,也会返回False
is also returned if the path doesn’t exist; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
is_socket
()¶ Return如果路径指向Unix套接字(或指向Unix套接字的符号链接),则返回True
if the path points to a Unix socket (or a symbolic link pointing to a Unix socket),False
if it points to another kind of file.True
;如果路径指向其他类型的文件,则返回False
。如果路径不存在或是断开的符号链接,也会返回False
is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
is_fifo
()¶ Return如果路径指向FIFO(或指向FIFO的符号链接),则返回True
if the path points to a FIFO (or a symbolic link pointing to a FIFO),False
if it points to another kind of file.True
;如果路径指向其他类型的文件,则返回False
。如果路径不存在或是断开的符号链接,也会返回False
is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
is_block_device
()¶ Return如果路径指向块设备(或指向块设备的符号链接),则返回True
if the path points to a block device (or a symbolic link pointing to a block device),False
if it points to another kind of file.True
;如果路径指向其他类型的文件,则返回False
。如果路径不存在或是断开的符号链接,也会返回False
is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
is_char_device
()¶ Return如果路径指向字符设备(或指向字符设备的符号链接),则返回True
if the path points to a character device (or a symbolic link pointing to a character device),False
if it points to another kind of file.True
;如果路径指向其他类型的文件,则返回False
。如果路径不存在或是断开的符号链接,也会返回False
is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.False
;传播其他错误(如权限错误)。
-
Path.
iterdir
()¶ When the path points to a directory, yield path objects of the directory contents:当路径指向目录时,生成目录内容的路径对象:>>> 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')The children are yielded in arbitrary order, and the special entries孩子们是按任意顺序产生的,特别的条目是'.'
and'..'
are not included.'.'
和'..'
不包括在内。If a file is removed from or added to the directory after creating the iterator, whether a path object for that file be included is unspecified.如果在创建迭代器后将文件从目录中删除或添加到目录中,则未指定是否包含该文件的路径对象。
-
Path.
lchmod
(mode)¶ Like与Path.chmod()
but, if the path points to a symbolic link, the symbolic link’s mode is changed rather than its target’s.Path.chmod()
类似,但如果路径指向符号链接,则符号链接的模式将更改,而不是其目标模式。
-
Path.
lstat
()¶ Like与Path.stat()
but, if the path points to a symbolic link, return the symbolic link’s information rather than its target’s.Path.stat()
类似,但如果路径指向符号链接,则返回符号链接的信息,而不是其目标的信息。
-
Path.
mkdir
(mode=511, parents=False, exist_ok=False)¶ Create a new directory at this given path.在此给定路径上创建新目录。If mode is given, it is combined with the process’如果给定了mode,它将与进程的umask
value to determine the file mode and access flags.umask
值相结合,以确定文件模式和访问标志。If the path already exists,如果路径已存在,则引发FileExistsError
is raised.FileExistsError
。If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX如果parents为mkdir -p
command).true
,则根据需要创建此路径的任何缺少的父级;它们是使用默认权限创建的,不考虑模式(模仿POSIX mkdir-p命令)。If parents is false (the default), a missing parent raises如果parents为FileNotFoundError
.false
(默认值),则缺少的父级将引发FileNotFoundError
。If exist_ok is false (the default),如果exist_ok为FileExistsError
is raised if the target directory already exists.false
(默认值),则如果目标目录已存在,则会引发FileExistsError
。If exist_ok is true,如果exist_ok为FileExistsError
exceptions will be ignored (same behavior as the POSIXmkdir -p
command), but only if the last path component is not an existing non-directory file.true
,将忽略FileExistsError
异常(与POSIXmkdir -p
命令的行为相同),但仅当最后一个路径组件不是现有的非目录文件时。Changed in version 3.5:版本3.5中更改:The exist_ok parameter was added.已添加exist_ok参数。
-
Path.
open
(mode='r', buffering=- 1, encoding=None, errors=None, newline=None)¶ Open the file pointed to by the path, like the built-in打开路径指向的文件,就像内置的open()
function does:open()
函数那样:>>> p = Path('setup.py')
>>> with p.open() as f:
... f.readline()
...
'#!/usr/bin/env python3\n'
-
Path.
owner
()¶ Return the name of the user owning the file.返回拥有该文件的用户的名称。如果在系统数据库中找不到文件的uid,则会引发KeyError
is raised if the file’s uid isn’t found in the system database.KeyError
。
-
Path.
read_bytes
()¶ Return the binary contents of the pointed-to file as a bytes object:以字节对象的形式返回指向文件的二进制内容:>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'New in version 3.5.版本3.5中新增。
-
Path.
read_text
(encoding=None, errors=None)¶ Return the decoded contents of the pointed-to file as a string:以字符串形式返回指向文件的解码内容:>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'The file is opened and then closed.文件打开后关闭。The optional parameters have the same meaning as in可选参数的含义与open()
.open()
中的相同。New in version 3.5.版本3.5中新增。
-
Path.
readlink
()¶ Return the path to which the symbolic link points (as returned by返回符号链接指向的路径(由os.readlink()
):os.readlink()
返回):>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.readlink()
PosixPath('setup.py')New in version 3.9.版本3.9中新增。
-
Path.
rename
(target)¶ Rename this file or directory to the given target, and return a new Path instance pointing to target.将此文件或目录重命名为给定target,并返回指向target的新路径实例。On Unix, if target exists and is a file, it will be replaced silently if the user has permission.在Unix上,如果target存在并且是一个文件,则如果用户有权限,它将被静默替换。target can be either a string or another path object:target可以是字符串或其他路径对象:>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
PosixPath('bar')
>>> target.open().read()
'some text'The target path may be absolute or relative.目标路径可以是绝对路径或相对路径。Relative paths are interpreted relative to the current working directory, not the directory of the Path object.相对路径是相对于当前工作目录而不是路径对象的目录进行解释的。Changed in version 3.8:版本3.8中更改:Added return value, return the new Path instance.添加返回值后,返回新路径实例。
-
Path.
replace
(target)¶ Rename this file or directory to the given target, and return a new Path instance pointing to target.将此文件或目录重命名为给定target,并返回指向target的新路径实例。If target points to an existing file or directory, it will be unconditionally replaced.如果target指向现有文件或目录,则将无条件替换它。The target path may be absolute or relative. Relative paths are interpreted relative to the current working directory, not the directory of the Path object.目标路径可以是绝对路径或相对路径。相对路径是相对于当前工作目录而不是路径对象的目录进行解释的。Changed in version 3.8:版本3.8中更改:Added return value, return the new Path instance.添加返回值后,返回新路径实例。
-
Path.
resolve
(strict=False)¶ Make the path absolute, resolving any symlinks. A new path object is returned:使路径为绝对路径,解析任何符号链接。返回新的路径对象:>>> p = Path()
>>> p
PosixPath('.')
>>> p.resolve()
PosixPath('/home/antoine/pathlib')“还消除了“..
” components are also eliminated (this is the only method to do so):..
”组件(这是唯一的方法):>>> p = Path('docs/../setup.py')
>>> p.resolve()
PosixPath('/home/antoine/pathlib/setup.py')If the path doesn’t exist and strict is如果路径不存在且strict为True
,FileNotFoundError
is raised.True
,则会引发FileNotFoundError
。If strict is如果strict为False
, the path is resolved as far as possible and any remainder is appended without checking whether it exists.False
,则尽可能解析路径,并附加任何余数,而不检查其是否存在。If an infinite loop is encountered along the resolution path,如果在解析路径上遇到无限循环,则会引发RuntimeError
is raised.RuntimeError
。New in version 3.6.版本3.6中新增。The strict argument (pre-3.6 behavior is strict).strict参数(3.6之前的行为是严格的)。
-
Path.
rglob
(pattern)¶ This is like calling这就像调用Path.glob()
with “**/
” added in front of the given relative 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')]Raises an auditing event使用参数pathlib.Path.rglob
with argumentsself
,pattern
.self
、pattern
引发审核事件pathlib.Path.rglob
。
-
Path.
rmdir
()¶ Remove this directory.删除此目录。The directory must be empty.目录必须为空。
-
Path.
samefile
(other_path)¶ Return whether this path points to the same file as other_path, which can be either a Path object, or a string.返回此路径是否指向与other_path相同的文件,该路径可以是路径对象,也可以是字符串。The semantics are similar to语义类似于os.path.samefile()
andos.path.samestat()
.os.path.samefile()
和os.path.samestat()
。An如果由于某种原因无法访问任一文件,则会引发OSError
can be raised if either file cannot be accessed for some reason.OSError
。>>> p = Path('spam')
>>> q = Path('eggs')
>>> p.samefile(q)
False
>>> p.samefile('spam')
TrueNew in version 3.5.版本3.5中新增。
-
Path.
symlink_to
(target, target_is_directory=False)¶ Make this path a symbolic link to target.使此路径成为指向target的符号链接。Under Windows, target_is_directory must be true (default在Windows下,如果链接的目标是目录,则target_is_directory必须为False
) if the link’s target is a directory.true
(默认为False
)。Under POSIX, target_is_directory’s value is ignored.在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
8Note
The order of arguments (link, target) is the reverse of参数(link,target)的顺序与os.symlink()
’s.os.symlink()
的顺序相反。
-
Path.
hardlink_to
(target)¶ Make this path a hard link to the same file as target.使此路径成为指向与target相同的文件的硬链接。Note
The order of arguments (link, target) is the reverse of参数的顺序(link,target)与os.link()
’s.os.link()
相反。New in version 3.10.版本3.10中新增。
-
Path.
link_to
(target)¶ Make target a hard link to this path.使target成为指向此路径的硬链接。Warning
This function does not make this path a hard link to target, despite the implication of the function and argument names.此函数不会使此路径成为指向target的硬链接,尽管函数和参数名称有含义。The argument order (target, link) is the reverse ofPath.symlink_to()
andPath.hardlink_to()
, but matches that ofos.link()
.Path.symlink_to()
的参数顺序(target,link)与Path.hardlink_to()
相反,但与os.link()
的参数顺序匹配。New in version 3.8.版本3.8中新增。Deprecated since version 3.10:自版本3.10以来已弃用:This method is deprecated in favor ofPath.hardlink_to()
, as the argument order ofPath.link_to()
does not match that ofPath.symlink_to()
.
-
Path.
touch
(mode=438, exist_ok=True)¶ Create a file at this given path.在此给定路径创建文件。If mode is given, it is combined with the process’umask
value to determine the file mode and access flags.If the file already exists, the function succeeds if exist_ok is true (and its modification time is updated to the current time), otherwise如果文件已经存在,如果exist_ok为FileExistsError
is raised.true
(并且其修改时间更新为当前时间),则函数将成功,否则将引发FileExistsError
。
-
Path.
unlink
(missing_ok=False)¶ Remove this file or symbolic link.删除此文件或符号链接。If the path points to a directory, use如果路径指向目录,请改用Path.rmdir()
instead.Path.rmdir()
。If missing_ok is false (the default),
FileNotFoundError
is raised if the path does not exist.If missing_ok is true,
FileNotFoundError
exceptions will be ignored (same behavior as the POSIXrm -f
command).Changed in version 3.8:版本3.8中更改: The missing_ok parameter was added.
-
Path.
write_bytes
(data)¶ Open the file pointed to in bytes mode, write data to it, and close the file:以字节模式打开指向的文件,向其中写入data,然后关闭文件:>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'An existing file of the same name is overwritten.将覆盖同名的现有文件。New in version 3.5.版本3.5中新增。
-
Path.
write_text
(data, encoding=None, errors=None, newline=None)¶ Open the file pointed to in text mode, write data to it, and close the file:以文本模式打开指向的文件,向其中写入data,然后关闭文件:>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'An existing file of the same name is overwritten.将覆盖同名的现有文件。The optional parameters have the same meaning as in可选参数的含义与open()
.open()
中的相同。New in version 3.5.版本3.5中新增。Changed in version 3.10:版本3.10中更改:The newline parameter was added.添加了newline参数。
Correspondence to tools in the os
module与os
模块中工具的对应关系¶
os
moduleBelow is a table mapping various 下表将各种os
functions to their corresponding PurePath
/Path
equivalent.os
函数映射到相应的PurePath
/Path
等效项。
Note
Not all pairs of functions/methods below are equivalent. 并非以下所有成对的函数/方法都是等效的。Some of them, despite having some overlapping use-cases, have different semantics. 其中一些,尽管有一些重叠的用例,但有不同的语义。They include 它们包括os.path.abspath()
and Path.resolve()
, os.path.relpath()
and PurePath.relative_to()
.os.path.abspath()
和Path.resolve()
、os.path.relpath()
和PurePath.relative_to()
。
|
|
Footnotes
- 1
os.path.abspath()
does not resolve symbolic links whilePath.resolve()
does.os.path.abspath()
不解析符号链接,而Path.resolve()
解析符号链接。- 2
Path.relative_to()
requiresself
to be the subpath of the argument, butos.path.relpath()
does not.Path.relative_to()
要求self
作为参数的子路径,但os.path.relpath()
不要求。