内容表

  • pathlib — 面向对象的文件系统路径
    • 基本用法
    • 纯路径
      • 一般特性
      • 运算符
      • 访问单个部分
      • 方法和特性
    • 具体路径
      • Querying file type and status
      • Reading and writing files
      • 其它方法
    • 对应工具在 os 模块

上一话题

文件和目录访问

下一话题
就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 文件和目录访问
  9. pathlib — 面向对象的文件系统路径

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

Added in version 3.4.

源代码: Lib/pathlib.py


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

../_images/pathlib-inheritance.png

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

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

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

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

另请参阅

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

另请参阅

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

基本用法 ¶

导入主类:

>>> from pathlib import Path
										

列出子目录:

>>> 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'
										

纯路径 ¶

纯路径对象提供不实际访问文件系统的路径处理操作。访问这些类有 3 种方式,也称为 flavours :

class pathlib. PurePath ( * pathsegments ) ¶

表示系统路径风味的一般类 (实例化它会创建 PurePosixPath 或 PureWindowsPath ):

>>> PurePath('setup.py')      # Running on a Unix machine
PurePosixPath('setup.py')
											

每元素的 pathsegments can be either a string representing a path segment, or an object implementing the os.PathLike interface where the __fspath__() method returns a string, such as another path object:

>>> PurePath('foo', 'some/path', 'bar')
PurePosixPath('foo/some/path/bar')
>>> PurePath(Path('foo'), Path('bar'))
PurePosixPath('foo/bar')
											

当 pathsegments 为空,则假定当前目录:

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

If a segment is an absolute path, all previous segments are ignored (like os.path.join() ):

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

On Windows, the drive is not reset when a rooted relative path segment (e.g., r'\foo' ) is encountered:

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

伪斜杠和单点会被折叠,但双点 ( '..' ) and leading double slashes ( '//' ) are not, since this would change the meaning of a path for various reasons (e.g. symbolic links, UNC paths):

>>> PurePath('foo//bar')
PurePosixPath('foo/bar')
>>> 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 接口。

class pathlib. PurePosixPath ( * pathsegments ) ¶

子类化的 PurePath ,此路径风味表示非 Windows 文件系统路径:

>>> PurePosixPath('/etc')
PurePosixPath('/etc')
											

pathsegments 的指定类似于 PurePath .

class pathlib. PureWindowsPath ( * pathsegments ) ¶

子类化的 PurePath , this path flavour represents Windows filesystem paths, including UNC paths :

>>> PureWindowsPath('c:/Program Files/')
PureWindowsPath('c:/Program Files')
>>> PureWindowsPath('//server/share/file')
PureWindowsPath('//server/share/file')
											

pathsegments 的指定类似于 PurePath .

不管在哪个系统中运行,可以实例化所有这些类,因为它们不提供任何做系统调用的操作。

一般特性 ¶

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
									

不同风味的路径比较不相等且无法排序:

>>> 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'
									

运算符 ¶

The slash operator helps create child paths, like os.path.join() . If the argument is an absolute path, the previous path is ignored. On Windows, the drive is not reset when the argument is a rooted relative path (e.g., r'\foo' ):

>>> p = PurePath('/etc')
>>> p
PurePosixPath('/etc')
>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')
>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')
>>> p / '/an_absolute_path'
PurePosixPath('/an_absolute_path')
>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
									

路径对象可用于任何地方的对象实现 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'
									

注意

调用 bytes 仅推荐在 Unix。在 Windows,Unicode 形式是文件系统路径的典型表示。

访问单个部分 ¶

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

PurePath. parts ¶

给出访问路径各组件的元组:

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

(注意,驱动和本地根是如何重新分组在一部分的)

方法和特性 ¶

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

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:

>>> 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:

>>> PureWindowsPath('//host/share').root
'\\'
										

If the path starts with more than two successive slashes, PurePosixPath collapses them:

>>> PurePosixPath('//etc').root
'//'
>>> PurePosixPath('///etc').root
'/'
>>> PurePosixPath('////etc').root
'/'
										

注意

This behavior conforms to The Open Group Base Specifications Issue 6 , paragraph 4.11 Pathname Resolution :

“A pathname that begins with two successive slashes may be interpreted in an implementation-defined manner, although more than two leading slashes shall be treated as a single slash.”

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:/')
										

3.10 版改变: The parents sequence now supports slices and negative index values.

PurePath. parent ¶

路径的逻辑父级:

>>> 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('.')
										

注意

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.

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:

>>> 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 ( ) ¶

将路径表示为 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 ( ) ¶

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 路径。

>>> p = PurePath('/etc/passwd')
>>> p.is_relative_to('/etc')
True
>>> p.is_relative_to('/usr')
False
												

This method is string-based; it neither accesses the filesystem nor treats “ .. ” segments specially. The following code is equivalent:

>>> u = PurePath('/usr')
>>> u == p or u in p.parents
False
													

Added in version 3.9.

Deprecated since version 3.12, will be removed in version 3.14: Passing additional arguments is deprecated; if supplied, they are joined with other .

PurePath. is_reserved ( ) ¶

采用 PureWindowsPath ,返回 True if the path is considered reserved under Windows, False otherwise. With PurePosixPath , False is always returned.

>>> PureWindowsPath('nul').is_reserved()
True
>>> PurePosixPath('nul').is_reserved()
False
														

File system calls on reserved paths can fail mysteriously or have unintended effects.

PurePath. joinpath ( * pathsegments ) ¶

Calling this method is equivalent to combining the path with each of the given pathsegments in turn:

>>> 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 , * , case_sensitive = None ) ¶

Match this path against the provided glob-style pattern. Return True if matching is successful, False 否则。

若 pattern is relative, the path can be either relative or absolute, and matching is done from the right:

>>> 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 is absolute, the path must be absolute, and the whole path must match:

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

The pattern may be another path object; this speeds up matching the same pattern against multiple files:

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

注意

The recursive wildcard “ ** ” isn’t supported by this method (it acts like non-recursive “ * ”.)

Changed in version 3.12: Accepts an object implementing the os.PathLike 接口。

As with other methods, case-sensitivity follows platform defaults:

>>> PurePosixPath('b.py').match('*.PY')
False
>>> PureWindowsPath('b.py').match('*.PY')
True
														

Set case_sensitive to True or False to override this behaviour.

Changed in version 3.12: The case_sensitive 参数被添加。

PurePath. relative_to ( other , walk_up = False ) ¶

Compute a version of this path relative to the path represented by other . If it’s impossible, 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 941, in relative_to
    raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not in the subpath of '/usr' OR one path is relative and the other is absolute.
														

当 walk_up is false (the default), the path must start with other . When the argument is true, .. entries may be added to form the relative path. In all other cases, such as the paths referencing different drives, ValueError is raised.:

>>> p.relative_to('/usr', walk_up=True)
PurePosixPath('../etc/passwd')
>>> p.relative_to('foo', walk_up=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pathlib.py", line 941, in relative_to
    raise ValueError(error_message.format(str(self), str(formatted)))
ValueError: '/etc/passwd' is not on the same drive as 'foo' OR one path is relative and the other is absolute.
														

警告

This function is part of PurePath and works with strings. It does not check or access the underlying file structure. This can impact the walk_up option as it assumes that no symlinks are present in the path; call resolve() first if necessary to resolve symlinks.

Changed in version 3.12: The walk_up parameter was added (old behavior is the same as walk_up=False ).

Deprecated since version 3.12, will be removed in version 3.14: Passing additional positional arguments is deprecated; if supplied, they are joined with other .

PurePath. with_name ( name ) ¶

返回的新路径带 name changed. If the original path doesn’t have a name, ValueError is raised:

>>> 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 ) ¶

返回的新路径带 stem changed. If the original path doesn’t have a name, ValueError is raised:

>>> 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 name
														

Added in version 3.9.

PurePath. with_suffix ( suffix ) ¶

返回的新路径带 suffix changed. 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:

>>> 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')
														
PurePath. with_segments ( * pathsegments ) ¶

Create a new path object of the same type by combining the given pathsegments . This method is called whenever a derivative path is created, such as from parent and relative_to() . Subclasses may override this method to pass information to derivative paths, for example:

from pathlib import PurePosixPath
class MyPath(PurePosixPath):
    def __init__(self, *pathsegments, session_id):
        super().__init__(*pathsegments)
        self.session_id = session_id
    def with_segments(self, *pathsegments):
        return type(self)(*pathsegments, session_id=self.session_id)
etc = MyPath('/etc', session_id=42)
hosts = etc / 'hosts'
print(hosts.session_id)  # 42
														

3.12 版添加。

具体路径 ¶

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

class pathlib. 路径 ( * pathsegments ) ¶

子类化的 PurePath ,此类表示系统路径风味的具体路径 (实例化它创建 PosixPath 或 WindowsPath ):

>>> Path('setup.py')
PosixPath('setup.py')
														

pathsegments 的指定类似于 PurePath .

class pathlib. PosixPath ( * pathsegments ) ¶

子类化的 Path and PurePosixPath ,此类表示非 Windows 文件系统具体路径:

>>> PosixPath('/etc')
PosixPath('/etc')
														

pathsegments 的指定类似于 PurePath .

class pathlib. WindowsPath ( * pathsegments ) ¶

子类化的 Path and PureWindowsPath ,此类表示 Windows 文件系统具体路径:

>>> WindowsPath('c:/Program Files/')
WindowsPath('c:/Program Files')
														

pathsegments 的指定类似于 PurePath .

只可以实例化对应系统风味的类 (允许系统调用不兼容风味路径,会导致应用程序 Bug 或故障):

>>> 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
												

Querying file type and status ¶

3.8 版改变: exists() , is_dir() , is_file() , is_mount() , is_symlink() , is_block_device() , is_char_device() , is_fifo() , is_socket() 现在返回 False instead of raising an exception for paths that contain characters unrepresentable at the OS level.

Path. stat ( * , follow_symlinks = True ) ¶

返回 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 ,或使用 lstat() .

>>> p = Path('setup.py')
>>> p.stat().st_size
956
>>> p.stat().st_mtime
1327883547.852554
														

3.10 版改变: The follow_symlinks 参数被添加。

Path. lstat ( ) ¶

像 Path.stat() but, if the path points to a symbolic link, return the symbolic link’s information rather than its target’s.

Path. exists ( * , follow_symlinks = True ) ¶

返回 True if the path points to an existing file or directory.

This method normally follows symlinks; to check if a symlink exists, add the argument follow_symlinks=False .

>>> Path('.').exists()
True
>>> Path('setup.py').exists()
True
>>> Path('/etc').exists()
True
>>> Path('nonexistentfile').exists()
False
														

Changed in version 3.12: The follow_symlinks 参数被添加。

Path. is_file ( ) ¶

返回 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.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path. is_dir ( ) ¶

返回 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.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path. is_symlink ( ) ¶

返回 True if the path points to a symbolic link, False 否则。

False is also returned if the path doesn’t exist; other errors (such as permission errors) are propagated.

Path. is_junction ( ) ¶

返回 True if the path points to a junction, and False for any other type of file. Currently only Windows supports junctions.

3.12 版添加。

Path. is_mount ( ) ¶

返回 True if the path is a mount point : a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path ’s parent, path/.. , is on a different device than path , or whether path/.. and path point to the same i-node on the same device — this should detect mount points for all Unix and POSIX variants. On Windows, a mount point is considered to be a drive letter root (e.g. c:\ ), a UNC share (e.g. \\server\share ), or a mounted filesystem directory.

Added in version 3.7.

Changed in version 3.12: 添加 Windows 支持。

Path. is_socket ( ) ¶

返回 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.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path. is_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.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path. is_block_device ( ) ¶

返回 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.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

Path. is_char_device ( ) ¶

返回 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.

False is also returned if the path doesn’t exist or is a broken symlink; other errors (such as permission errors) are propagated.

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. The semantics are similar to os.path.samefile() and os.path.samestat() .

An OSError can be raised if either file cannot be accessed for some reason.

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

Added in version 3.5.

Reading and writing files ¶

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:

>>> p = Path('setup.py')
>>> with p.open() as f:
...     f.readline()
...
'#!/usr/bin/env python3\n'
														
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() .

Added in version 3.5.

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'
														

Added in version 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:

>>> 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() .

Added in version 3.5.

3.10 版改变: The newline 参数被添加。

Path. write_bytes ( data ) ¶

Open the file pointed to in bytes mode, write data to it, and close the file:

>>> 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.

Added in version 3.5.

其它方法 ¶

Many of these methods can raise an OSError if a system call fails (for example because the path doesn’t exist).

classmethod Path. cwd ( ) ¶

返回表示当前目录的新路径对象 (如返回通过 os.getcwd() ):

>>> Path.cwd()
PosixPath('/home/antoine/pathlib')
														
classmethod Path. home ( ) ¶

返回表示用户 Home (主) 目录的新路径对象 (如返回通过 os.path.expanduser() with ~ construct). If the home directory can’t be resolved, RuntimeError 被引发。

>>> Path.home()
PosixPath('/home/antoine')
														

Added in version 3.5.

Path. chmod ( mode , * , follow_symlinks = True ) ¶

更改文件模式和权限,像 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 follow_symlinks=False ,或使用 lchmod() .

>>> p = Path('setup.py')
>>> p.stat().st_mode
33277
>>> p.chmod(0o444)
>>> p.stat().st_mode
33060
														

3.10 版改变: The follow_symlinks 参数被添加。

Path. expanduser ( ) ¶

Return a new path with expanded ~ and ~user constructs, as returned by os.path.expanduser() . If a home directory can’t be resolved, RuntimeError 被引发。

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

Added in version 3.5.

Path. glob ( pattern , * , case_sensitive = None ) ¶

Glob the given relative pattern in the directory represented by this path, yielding all matching files (of any kind):

>>> 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”. 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')]
														

此方法调用 Path.is_dir() on the top-level directory and propagates any OSError exception that is raised. Subsequent OSError exceptions from scanning directories are suppressed.

By default, or when the case_sensitive keyword-only argument is set to None , this method matches paths using platform-specific casing rules: typically, case-sensitive on POSIX, and case-insensitive on Windows. Set case_sensitive to True or False to override this behaviour.

注意

使用 ** 模式在大型目录树中可能消耗过多时间。

引发 审计事件 pathlib.Path.glob 采用自变量 self , pattern .

3.11 版改变: Return only directories if pattern ends with a pathname components separator ( sep or altsep ).

Changed in version 3.12: The case_sensitive 参数被添加。

Path. group ( ) ¶

Return the name of the group owning the file. KeyError is raised if the file’s gid isn’t found in the system database.

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. walk ( top_down = True , on_error = None , follow_symlinks = False ) ¶

Generate the file names in a directory tree by walking the tree either top-down or bottom-up.

For each directory in the directory tree rooted at self (including self but excluding ‘.’ and ‘..’), the method yields a 3-tuple of (dirpath, dirnames, filenames) .

dirpath 是 Path to the directory currently being walked, dirnames is a list of strings for the names of subdirectories in dirpath (excluding '.' and '..' ),和 filenames is a list of strings for the names of the non-directory files in dirpath . To get a full path (which begins with self ) to a file or directory in dirpath , do dirpath / name . Whether or not the lists are sorted is file system-dependent.

If the optional argument top_down is true (which is the default), the triple for a directory is generated before the triples for any of its subdirectories (directories are walked top-down). If top_down is false, the triple for a directory is generated after the triples for all of its subdirectories (directories are walked bottom-up). No matter the value of top_down , the list of subdirectories is retrieved before the triples for the directory and its subdirectories are walked.

当 top_down is true, the caller can modify the dirnames list in-place (for example, using del or slice assignment), and Path.walk() will only recurse into the subdirectories whose names remain in dirnames . This can be used to prune the search, or to impose a specific order of visiting, or even to inform Path.walk() about directories the caller creates or renames before it resumes Path.walk() again. Modifying dirnames 当 top_down is false has no effect on the behavior of Path.walk() since the directories in dirnames have already been generated by the time dirnames is yielded to the caller.

By default, errors from os.scandir() are ignored. If the optional argument on_error is specified, it should be a callable; it will be called with one argument, an OSError instance. The callable can handle the error to continue the walk or re-raise it to stop the walk. Note that the filename is available as the filename attribute of the exception object.

默认情况下, Path.walk() does not follow symbolic links, and instead adds them to the filenames list. Set follow_symlinks to true to resolve symlinks and place them in dirnames and filenames as appropriate for their targets, and consequently visit directories pointed to by symlinks (where supported).

注意

Be aware that setting follow_symlinks to true can lead to infinite recursion if a link points to a parent directory of itself. Path.walk() does not keep track of the directories it has already visited.

注意

Path.walk() assumes the directories it walks are not modified during execution. For example, if a directory from dirnames has been replaced with a symlink and follow_symlinks 为 False, Path.walk() will still try to descend into it. To prevent such behavior, remove directories from dirnames 酌情。

注意

不像 os.walk() , Path.walk() lists symlinks to directories in filenames if follow_symlinks 为 False。

This example displays the number of bytes used by all files in each directory, while ignoring __pycache__ directories:

from pathlib import Path
for root, dirs, files in Path("cpython/Lib/concurrent").walk(on_error=print):
  print(
      root,
      "consumes",
      sum((root / file).stat().st_size for file in files),
      "bytes in",
      len(files),
      "non-directory files"
  )
  if '__pycache__' in dirs:
        dirs.remove('__pycache__')
														

This next example is a simple implementation of shutil.rmtree() . Walking the tree bottom-up is essential as rmdir() doesn’t allow deleting a directory before it is empty:

# Delete everything reachable from the directory "top".
# CAUTION:  This is dangerous! For example, if top == Path('/'),
# it could delete all of your files.
for root, dirs, files in top.walk(top_down=False):
    for name in files:
        (root / name).unlink()
    for name in dirs:
        (root / name).rmdir()
														

3.12 版添加。

Path. lchmod ( mode ) ¶

像 Path.chmod() but, if the path points to a symbolic link, the symbolic link’s mode is changed rather than its target’s.

Path. mkdir ( mode = 0o777 , parents = False , exist_ok = False ) ¶

Create a new directory 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 path already exists, FileExistsError 被引发。

若 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 mkdir -p 命令)。

若 parents is false (the default), a missing parent raises FileNotFoundError .

若 exist_ok 为 False (默认), FileExistsError 被引发若目标目录已存在。

若 exist_ok 为 True, FileExistsError will not be raised unless the given path already exists in the file system and is not a directory (same behavior as the POSIX mkdir -p 命令)。

3.5 版改变: The exist_ok 参数被添加。

Path. owner ( ) ¶

Return the name of the user owning the file. KeyError is raised if the file’s uid isn’t found in the system database.

Path. readlink ( ) ¶

Return the path to which the symbolic link points (as returned by os.readlink() ):

>>> p = Path('mylink')
>>> p.symlink_to('setup.py')
>>> p.readlink()
PosixPath('setup.py')
														

Added in version 3.9.

Path. rename ( target ) ¶

Rename this file or directory to the given target , and return a new Path instance pointing to target . On Unix, if target exists and is a file, it will be replaced silently if the user has permission. On Windows, if target exists, FileExistsError 会被引发。 target can be either a string or another path object:

>>> 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.

It is implemented in terms of os.rename() and gives the same guarantees.

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 points to an existing file or empty directory, it will be unconditionally replaced.

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.

3.8 版改变: Added return value, return the new Path instance.

Path. absolute ( ) ¶

Make the path absolute, without normalization or resolving symlinks. Returns a new path object:

>>> p = Path('tests')
>>> p
PosixPath('tests')
>>> p.absolute()
PosixPath('/home/antoine/pathlib/tests')
														
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')
														

若路径不存在且 strict is True , FileNotFoundError 被引发。若 strict is False , the path is resolved as far as possible and any remainder is appended without checking whether it exists. If an infinite loop is encountered along the resolution path, RuntimeError 被引发。

3.6 版改变: The strict parameter was added (pre-3.6 behavior is strict).

Path. rglob ( pattern , * , case_sensitive = None ) ¶

Glob the given relative pattern recursively. This is like calling Path.glob() with “ **/ ” added in front of the pattern ,其中 patterns are the same as for fnmatch :

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

By default, or when the case_sensitive keyword-only argument is set to None , this method matches paths using platform-specific casing rules: typically, case-sensitive on POSIX, and case-insensitive on Windows. Set case_sensitive to True or False to override this behaviour.

引发 审计事件 pathlib.Path.rglob 采用自变量 self , pattern .

3.11 版改变: Return only directories if pattern ends with a pathname components separator ( sep or altsep ).

Changed in version 3.12: The case_sensitive 参数被添加。

Path. rmdir ( ) ¶

移除此目录。目录必须为空。

Path. symlink_to ( target , target_is_directory = False ) ¶

Make this path a symbolic link pointing to target .

On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is True or a file symlink (the default) otherwise. On non-Windows platforms, 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
														

注意

The order of arguments (link, target) is the reverse of os.symlink() ’s.

Path. hardlink_to ( target ) ¶

Make this path a hard link to the same file as target .

注意

The order of arguments (link, target) is the reverse of os.link() ’s.

Added in version 3.10.

Path. touch ( mode = 0o666 , exist_ok = True ) ¶

在此给定路径创建文件。若 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 FileExistsError 被引发。

Path. unlink ( missing_ok = False ) ¶

移除此文件或符号链接。若路径指向目录,使用 Path.rmdir() 代替。

若 missing_ok 为 False (默认), FileNotFoundError 被引发若路径不存在。

若 missing_ok 为 True, FileNotFoundError 异常将被忽略 (相同行为如 POSIX rm -f 命令)。

3.8 版改变: The missing_ok 参数被添加。

对应工具在 os 模块 ¶

下表映射各种 os 函数到其相应 PurePath / Path 等价。

注意

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.absolute() , os.path.relpath() and PurePath.relative_to() .

os and os.path

pathlib

os.path.abspath()

Path.absolute() [ 1 ]

os.path.realpath()

Path.resolve()

os.chmod()

Path.chmod()

os.mkdir()

Path.mkdir()

os.makedirs()

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() and Path.home()

os.listdir()

Path.iterdir()

os.walk()

Path.walk()

os.path.isdir()

Path.is_dir()

os.path.isfile()

Path.is_file()

os.path.islink()

Path.is_symlink()

os.link()

Path.hardlink_to()

os.symlink()

Path.symlink_to()

os.readlink()

Path.readlink()

os.path.relpath()

PurePath.relative_to() [ 2 ]

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.stem and PurePath.suffix

脚注

[ 1 ]

os.path.abspath() normalizes the resulting path, which may change its meaning in the presence of symlinks, while Path.absolute() 不会。

[ 2 ]

PurePath.relative_to() requires self to be the subpath of the argument, but os.path.relpath() 不会。

内容表

  • pathlib — 面向对象的文件系统路径
    • 基本用法
    • 纯路径
      • 一般特性
      • 运算符
      • 访问单个部分
      • 方法和特性
    • 具体路径
      • Querying file type and status
      • Reading and writing files
      • 其它方法
    • 对应工具在 os 模块

上一话题

文件和目录访问

下一话题

os.path — 常见路径名操纵

本页

  • 报告 Bug
  • 展示源

快速搜索

键入搜索术语或模块、类、函数名称。

  1. 首页
  2. Python 3.12.4
  3. 索引
  4. 模块
  5. 下一
  6. 上一
  7. Python 标准库
  8. 文件和目录访问
  9. pathlib — 面向对象的文件系统路径

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1