pathlib - Object-oriented filesystem paths

此模块提供表示文件系统路径的类,其语义适用于不同的操作系统。 路径类分为:

pathlib

基本使用

导入 Path

PYTHON
from pathlib import Path
p = Path('.')
Click to expand and view more

列出所有子目录

PYTHON
[x for x in p.iterdir() if x.is_dir()]
Click to expand and view more

列出所有 py 源码文件

PYTHON
list(p.glob('**/*.py'))
Click to expand and view more

在目录树中移动

PYTHON
p = Path('/etc')
q = p / 'init.d' / 'reboot'
# .resolve() 方法会解析所有符号链接,返回文件绝对路径
# mac os 中的 /etc 实际上是一个符号链接,指向 /private/etc
q.resolve()
Click to expand and view more

查询文件路径

PYTHON
q.exists() # 文件是否存在
q.is_dir() # 是否为目录
Click to expand and view more

打开一个文件

PYTHON
q = Path('.') / 'file.py'
with q.open() as f:
    # 读取第一行内容
    f.readline()
Click to expand and view more

Pure paths 纯路径

Pure path 对象提供路径处理操作,这些操作无需真的访问操作系统。 有三种方法来操作这些类,也被称为 flavours (风格):

General properties 通用属性

Paths 是不可变且可哈希的 hashable,且同种风格的 Path 是可对比和可排序的。这些属性遵循风格的大小写折叠语义:

PYTHON
# Unix 大小写敏感
>>> PurePosixPath('foo') == PurePosixPath('Foo')
False

# Windows 大小写不敏感
>>> PureWindowsPath('foo') == PurePosixPath('FOO')
True
>>> PureWindowsPath('FOO') in { PureWindowsPath('foo') }
True

>>> PureWindowsPath('C:') < PureWindowsPath('D:')
True
Click to expand and view more

不同风格路径比较会得到不等的结果,且无法排序:

PYTHON
>>> 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'
Click to expand and view more

Operators 运算符

斜杠操作符可以创建子路径,如 os.path.join()。如果参数本身就是绝对路径,则该路径会替换原来路径;在 Windows 上,当参数为带根符号的相对路径,驱动器不会被重置。

PYTHON
>>> p = PurePath('/etc')
PurePosixPath('/etc')

>>> p / 'init.d' / 'apache2'
PurePosixPath('/etc/init.d/apache2')

>>> p / '/an_absolute_path'
PurePosixPath('/an_absolute_path')

>>> q = PurePath('bin')
>>> '/usr' / q
PurePosixPath('/usr/bin')

>>> PureWindowsPath('c:/Windows', '/Program Files')
PureWindowsPath('c:/Program Files')
Click to expand and view more

os.PathLike 是一个协议接口,任何实现了这个接口的对象都可以被 Python 的文件系统相关函数识别为有效的路径。

PYTHON
import os
p = PurePath('/etc')
os.fspath(p) # '/etc'
Click to expand and view more

路径的字符串表示形式,可以是系统路径形式,可以将其传递给任何文件路径作为字符串函数:

PYTHON
p = PurePath('/etc')
str(p) # '/etc'

p = PureWindowsPath('c:/Program Files')
str(p) # 'c:\\Program Files'
Click to expand and view more

Accessing individual parts 访问各个部分

使用下面属性来访问不同部分:

Methods and properties 方法和属性

Pure path 纯路径提供了下面的方法和属性:

Concrete paths 具体路径

具体路径是存路径的子类,该类型额外提供了系统调用路径对象的方法,有三种方法实例化具体路径:

只能在系统中实例化相同风格的 Path,否则错误

PYTHON
>>> 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
Click to expand and view more

Expanding and resolving paths 扩展和解析路径

Query flie type and status 查询文件类型和状态

Reading and writing file 读写文件

Reading directories 读取目录

Creating files and directories 创建文件和目录

Renaming and deleting 重命名和删除

Permissions and ownership 权限和所有权

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut