Python 中的面向对象文件系统路径 (pathlib)
pathlib 模块提供了一种面向对象的方法来处理文件系统路径。该模块还提供适用于各种操作系统的功能。此模块中定义的类有两种类型 - 纯路径类型和具体路径类型。虽然纯路径只能执行纯计算操作,但具体路径也能够执行 I/O 操作。
pathlib 模块定义以下类 −
Sr.No. | 模块 &描述 |
---|---|
1 | PurePath 所有其他类的基类 |
2 | Path 从 PurePath 中子类化。这是一个表示文件系统路径的具体类。 |
3 | PosixPath 非 Windows 操作系统的 Path 子类 |
4 | WindowsPath Windows 系统的 Path 子类 |
5 | PurePosixPath 非 Windows 系统的 PurePath 子类 |
6 | PureWindowsPath Windows 系统的 PurePath 子类 |
当创建 Path 类的实例时,它将根据您的系统自动返回 WindowsPath 或 PosixPath。
请注意,WindowsPath 或 PosixPath 对象也可以直接创建,但不能只在相同类型的系统上创建。
要创建 Path 对象,请使用以下语法
>>> from pathlib import * >>> p = Path(".") >>> type(p) <class 'pathlib.WindowsPath'>
您可以看到,由于上述语句是在 Windows 系统上执行的,因此创建了 WindowsPath 对象。“.” 指的是当前目录。
Path 类中定义了以下方法
absolute() − 返回 Path 对象的绝对版本。
>>> p.absolute() WindowsPath('C:/python36')
exists() 如果给定路径存在,− 将返回 true
>>> p = Path("mydir") >>> p.exists() False >>> p = Path("etc") >>> p.exists() True
is_dir() − 如果路径是目录则返回 true
>>> p = Path("etc") >>> p.is_dir() True >>> p = Path("test.py") >>> p.is_dir() False
is_file() − 如果路径对应于文件则返回 true
>>> p = Path("tmp.py") >>> p.is_file() True >>> p = Path("etc") >>> p.is_file() False
iterdir() − 返回一个生成器,该生成器生成与路径对应的目录中的文件名。
>>> p = Path("libs") >>> for f in p.iterdir(): print (f) libs\libpython36.a libs\python3.lib libs\python36.lib libs\_tkinter.lib
mkdir() − 如果路径尚不存在,则创建表示路径的新目录。
>>> p = Path("mydir") >>> p.mkdir() >>> p.absolute() WindowsPath('C:/python36/mydir') >>> p = Path("codes") >>> p.mkdir() FileExistsError: [WinError 183] 如果文件已存在,则无法创建文件:'codes'
open() − 打开 Path 对象表示的文件并返回文件对象。这类似于内置的 open() 函数。
>>> p = Path("Hello.py") >>> f = p.open() >>> f.readline() 'Hello Python'
read_bytes() − 以二进制模式打开文件,以二进制形式读取其数据并关闭。
>>> p = Path("Hello.py") >>> f.read_bytes() >>> p.read_bytes() b'Hello Python'
read_text() − 文件以文本模式打开以读取文本,然后关闭。
>>> p = Path("Hello.py") >>> p.read_text() 'Hello Python'
write_text() − 打开文件,写入文本并关闭。
>>> p = Path("Hello.py") >>> p.write_text("Hello how are you?") 18
write_bytes() − 将二进制数据写入文件并关闭该文件。
>>> p = Path("Hello.py") >>> p.write_bytes(b'I am fine') 9
stat() − 返回有关此路径的信息。
>>> p.stat() os.stat_result(st_mode = 16895, st_ino = 9570149208167477, st_dev = 1526259762, st_nlink = 1, st_uid = 0, st_gid = 0, st_size = 0, st_atime = 1543085915, st_mtime = 1543085915, st_ctime = 1543085915)
rmdir() − 删除与 Path 对象对应的目录。
>>> p = Path("mydir") >>> p.rmdir()
Path.cwd() − 这是 Path 类的一个类方法。返回当前工作目录的路径
>>> Path.cwd() WindowsPath('C:/python36')
Path.home() − 这是 Path 类的一个类方法。返回主目录的路径
>>>> Path.home() WindowsPath('C:/Users/acer')
‘/’ 运算符用于构建路径。
>>> p = Path(".") >>> p1 = p/'codes' >>> p1.absolute() WindowsPath('C:/python36/codes')
在本文中,我们学习了 pathlib 模块中定义的文件系统对象的面向对象 API。