Python 3.7.1 模块 pathlib

19 篇文章 1 订阅
11 篇文章 0 订阅

目录

版本3.4中的新功能。

源代码: Lib / pathlib.py


该模块提供表示文件系统路径的类,其语义适用于不同的操作系统。路径类划分为纯路径(pure paths)和具体路径( concrete paths),纯路径提供纯粹的计算操作而没有I/O,具体路径继承自纯路径但提供I/O操作。
在这里插入图片描述

如果您之前从未使用过此模块,或者只是不确定哪个类适合您的任务,Path则很可能是您需要的。它实例化运行代码的平台的具体路径。

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

  1. 如果要在Unix计算机上操作Windows路径(反之亦然)。WindowsPath在Unix上运行时无法实例化,但可以实例化PureWindowsPath
  2. 您希望确保您的代码仅操作路径而不实际访问操作系统。在这种情况下,实例化其中一个纯类可能很有用,因为那些只是没有任何操作系统访问。

也可以看看 PEP 428:pathlib模块 - 面向对象的文件系统路径。
也可以看看 对于字符串的低级路径操作,您也可以使用该 os.path模块。

1.基本使用

导入主类:

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

2. 纯路径(Pure paths)

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

2.1 类

class pathlib.PurePath(*pathsegments)

表示系统路径风格的泛型类(实例化它通过创建一个PurePosixPathPureWindowsPath):

>>>
>>> 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接口的支持。

class pathlib.PurePosixPath(*pathsegments)

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

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

pathsegments类似于指定PurePath。

class pathlib.PureWindowsPath(*pathsegments)

PurePath 的子类,表示Windows文件系统路径:

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

pathsegments类似于指定PurePath。

无论您运行的是哪个系统,都可以实例化所有这些类,因为它们不提供任何进行系统调用的操作。

2.2 常规属性

路径是不可变的和可清除的。相同风格的路径是可比较的和可排序的。这些属性尊重折叠语义:

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

2.3 操作

斜杠运算符有助于创建子路径,类似于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')

path对象可以在一个实现了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格式是文件系统路径的规范表示。

2.4 访问路径的各部分

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

PurePath.parts

一个元组,可以访问路径的各个组件:

>>>
>>> p = PurePath('/usr/bin/python3')
>>> p.parts
('/', 'usr', 'bin', 'python3')

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

(注意驱动器和本地根如何重新组合在一个部件中)

2.5 方法和属性

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

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

注意 这是一个纯粹的词法操作,因此有以下行为:

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

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

PurePath.name

表示最终路径组件的字符串,不包括驱动器和根目录(如果有):

>>>
>>> PurePosixPath('my/library/setup.py').name
'setup.py'

不考虑UNC驱动器名称:

>>>
>>> PureWindowsPath('//some/share/setup.py').name
'setup.py'
>>> PureWindowsPath('//some/share').name
''

PurePath.suffix

最终组件的文件扩展名(如果有):

>>>
>>> PurePosixPath('my/library/setup.py').suffix
'.py'
>>> PurePosixPath('my/library.tar.gz').suffix
'.gz'
>>> PurePosixPath('my/library').suffix
''

PurePath.suffixes

路径文件扩展名列表:

>>>
>>> PurePosixPath('my/library.tar.gar').suffixes
['.tar', '.gar']
>>> PurePosixPath('my/library.tar.gz').suffixes
['.tar', '.gz']
>>> PurePosixPath('my/library').suffixes
[]

PurePath.stem

最终路径组件,没有后缀:

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

将路径表示为一个fileURI。 如果路径不是绝对路径则会引发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)

调用此方法相当于将路径依次与每个其他参数组合:

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

将此路径与提供的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

与其他方法一样,可以分辨是否要区分大小写:

>>>
>>> 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更改后的新路径。如果原始路径没有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)

返回更改的带有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')

3.具体路径(Concrete paths)

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

3.1 类

class pathlib.Path(*pathsegments)

PurePath的子类表示具体路径(实例化它将会创建一个PosixPath或WindowsPath):

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

pathsegments类似于PurePath。

class pathlib.PosixPath(*pathsegments)

Path的子类,这个类表示具体的非Windows文件系统的路径:

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

pathsegments类似于PurePath。

class pathlib.WindowsPath(*pathsegments)

Path的子类,这个类表示具体的Windows文件系统的路径

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

3.2 方法

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

classmethod Path.cwd()

返回一个表示当前目录的新路径对象(同os.getcwd()的返回):

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

classmethod Path.home()

返回代表用户的主目录(如os.path.expanduser()返回的与~一起):

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

版本3.5中的新功能。

Path.stat()

返回有关此路径的信息(类似于os.stat())。结果是查看每次调用此方法。

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

Path.chmod(mode)

更改文件模式和权限,同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

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

Path.expanduser()

返回带有扩展~~user构造的新路径,同os.path.expanduser():

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

版本3.5中的新功能。

Path.glob(mode)

在当前目录针对给定模式进行匹配,产生所有匹配的文件(任何类型):

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

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

Path.group()

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

译者注:windows不支持。

Path.is_dir()

如果路径指向目录(或指向目录的符号链接)返回True,如果它指向另一个类型的文件则返回False。

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

Path.is_file()

如果路径指向一个普通文件(或指向一个普通文件的符号链接)返回True,如果它指向另一个类型的文件返回False。

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

Path.is_mount()

如果路径是挂载点,则返回True。在POSIX上,该函数检查路径的父节点(path/..)是否在与路径不同的设备上,或者路径是否指向同一设备上的同一个节点 - 这应该检测所有Unix和POSIX变体的挂载点。未在Windows上实现。

版本3.7中的新功能。

Path.is_symlink()

如果路径指向符号链接,则返回True,否则返回False。

如果路径不存在,也会返回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(mode)

就像Path.chmod()。但是,如果路径指向符号链接,该符号链接的方式被改变,而不是它的目标被改变。

Path.lstat()

就像Path.stat()。但是,如果路径指向符号链接,返回符号链接的信息,而不是它的目标的信息。

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

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

如果parents=True,那么根据需要创建path的任何不存在的父级路径; 它们是使用默认权限创建的,不考虑 mode(模仿POSIXmkdir -p命令)。

如果parents=False,任何不存在的父级路径将会导致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异常,widows不支持。

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中的新功能。

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中的新功能。

Path.rename(target)

将此文件或目录重命名为给定目标。在Unix上,如果 target存在并且是一个文件,如果用户有权限,它将被静默替换。 target可以是字符串或其他路径对象:

>>>
>>> p = Path('foo')
>>> p.open('w').write('some text')
9
>>> target = Path('bar')
>>> p.rename(target)
>>> target.open().read()
'some text'

Path.replace(target)

将此文件或目录重命名为给定目标。如果目标指向现有文件或目录,则将无条件地替换它。

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=False,报错FileNotFoundError 。如果strict=False,路径尽可能resolve。如果在resolve路径上遇到无限循环,则引发RuntimeError。

3.6版本:strict参数。

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)

返回此路径是否指向与other_path相同的文件,other_path可以是Path对象,也可以是字符串。语义类似于os.path.samefile()os.path.samestat()

如果两个文件不能因为某些原因被访问会报错OSError。

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

版本3.5中的新功能。

Path.symlink_to(target, target_is_directory=False)

使此路径成为目标的符号链接。在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

注意 参数的顺序与os.symlink() 的相反。

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

在此给定路径创建文件。如果给出了mode,则将其与进程的 umask值组合以确定文件模式和访问标志。如果文件已存在,则如果exist_ok=true(并且其修改时间更新为当前时间),则函数成功,否则引发FileExistsError

Path.unlink()

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

Path.write_bytes(data)

打开以字节模式指向的文件,向其写入数据,然后关闭文件:

>>>
>>> p = Path('my_binary_file')
>>> p.write_bytes(b'Binary file contents')
20
>>> p.read_bytes()
b'Binary file contents'

将覆盖现有的同名文件。

版本3.5中的新功能。

Path.write_text(data, encoding=None, errors=None)

打开文本模式指向的文件,向其写入数据,然后关闭文件:

>>>
>>> p = Path('my_text_file')
>>> p.write_text('Text file contents')
18
>>> p.read_text()
'Text file contents'

版本3.5中的新功能。

4. 对应os模块中的函数

下面是将各种os函数映射到其对应 PurePath/ Path等效的函数的表。

注意 虽然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
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值