Python中的面向对象文件系统路径 (pathlib)
pathlib模块提供了一种面向对象的方法来处理文件系统路径。该模块还提供了适用于各种操作系统的功能。此模块中定义的类分为两种类型——纯路径类型和具体路径类型。纯路径只能执行纯计算操作,而具体路径也能够执行I/O操作。
pathlib模块定义了以下类:
| 序号 | 模块及描述 |
|---|---|
| 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] Cannot create a file when that file already exists: '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。
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP