简介

Pathlib 是一个用于处理文件路径的 Python 库,提供了许多实用的函数和方法来处理文件系统路径。它提供了一个面向对象的层次结构,路径被表示为对象,这些对象拥有一些属性和方法,使得文件路径的操作变得更加直观和方便。

需要注意的是,pathlib 是 Python 3.4 以上版本引入的库,在 Python 3.10 版本中得到了显著的增强。读者需注意自己的 Python 版本是否支持。

Pathlib 库实现

Path 创建路径对象

Path 是 pathlib 库的核心类,它提供了一个高层次的接口来处理文件系统路径。通过 Path 类,你可以执行各种文件系统操作,如创建、删除、移动文件和目录,以及查询路径信息和列出目录内容等。

所以使用 Pathlib 库,首先需要我们创建路径对象:

1
2
3
4
5
6
from pathlib import Path

# 通过绝对路径地址创建路径对象 p_1
p_1 = Path('D:\Code_Learner\Python\Pathlib\main.py')
# 通过相对路径地址创建路径对象 p_2
p_2 = Path('.')

检查路径类型

.is_file():检查是否是文件;
.is_dir():检查是否是目录;
.exists():检查路径是否存在;

1
2
3
4
5
6
if p_1.is_file():
print("It's a file.")
if p_1.is_dir():
print("It's a directory.")
if p_1.exists():
print("The path exists.")

输出:

1
2
It's a file.
The path exists.

创建和删除路径(目录与文件)

.mkdir():创建目录;
.rmdir():删除目录;
.touch():创建空文件;
.unlink():删除文件;

1
2
3
4
5
6
7
# 绝对路径下创建文件夹
Path(r'D:\Code_Learner\test').mkdir()
# 相对路径下操作
Path('new_dir').mkdir()
Path('del_dir').rmdir()
Path('new_file.txt').touch()
Path('rm_file.txt').unlink()

读写文件

.read_text():读取文件内容;
.write_text():写入文件内容;

1
2
content = Path('example.txt').read_text()
Path('new_file.txt').write_text(content)

需要注意的是,写入文件内容操作为覆盖写入。

路径匹配

.glob():匹配路径模式;
.rglob():递归匹配路径模式;
e.g. 示例,找到路径下所有 .txt 文件;

1
2
for file in p_2.glob('*.txt'):
print(file)

路径拼接和解析

.joinpath():拼接路径;
.relative_to():获取相对路径;
.resolve():解析路径,返回绝对路径;
.parent:获取父目录;

1
2
3
4
5
6
7
8
9
# 拼接路径
subpath = Path('subdir') / 'subfile.txt'
print(subpath)
# 获取绝对路径
absolute_path = subpath.resolve()
print(absolute_path)
# 获取相对路径
relative_path = absolute_path.relative_to('D:/Code_Learner/Python/Pathlib')
print(relative_path)

e.g. 获取父目录地址

1
2
3
4
5
6
7
8
9
10
from pathlib import Path

# 创建一个路径对象
path = Path('C:/Users/example/documents/file.txt')

# 获取父目录
parent_dir = path.parent

# 打印父目录
print(parent_dir)

路径属性

.name:获取路径的文件名;
.with_name():修改文件名;
.suffix:获取文件的后缀;
.with_suffix():修改文件后缀;
.stem:获取文件名(不包含后缀)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from pathlib import Path

p = Path('.') / 'test.txt'
p = p.resolve()
print(p)
print(p.name)
print(p.suffix)
print(p.stem)

new_path = p.with_name('new_file.txt')
print(new_path)
new_path = new_path.with_suffix('.py')
print(new_path)
new_path = new_path.with_name('hello.md')
print(new_path)

注意修改文件名称同时会修改后缀内容,且修改文件名称和后缀名并非会修改源文件上的名称和后缀。如果想更改源文件上的名称和后缀,请使用 .rename() 方法。

路径迭代和列出目录内容

.iterdir():迭代目录内容;
.rglob():递归列出目录内容;
e.g. 获取指定目录下所有文件:

1
2
for entry in Path('.').iterdir():
print(entry)

e.g. 递归出指定目录下所有符合指定条件的文件:

假设我们的文件目录结构为:

1
2
3
4
5
6
# D:\Code_Learner\Python\Pathlib\test
- test
- test4.txt
- test1.txt
- test2.txt
- test3.txt

1
2
3
4
5
6
from pathlib import Path

p = Path(r'D:\Code_Learner\Python\Pathlib\test')

for entry in p.rglob('*.txt'):
print(entry)

结果为:

1
2
3
4
D:\Code_Learner\Python\Pathlib\test\test1.txt
D:\Code_Learner\Python\Pathlib\test\test2.txt
D:\Code_Learner\Python\Pathlib\test\test3.txt
D:\Code_Learner\Python\Pathlib\test\test\test4.txt

通过 rglob() 函数,递归遍历出了当前目录下所有满足条件的 .txt 文件,同时也递归出其下属文件夹 test 中的 test4.txt 文件

小结

上述这些函数和方法提供了处理文件系统路径所需的大部分功能。Pathlib 提供了一个面向对象的方式来处理文件系统路径,使得文件操作更加简洁、易于理解和维护。它是 Python 编程中处理文件路径的首选方法之一。