外观
pathlib
与文件系统交互是任何编程语言在本地开发中非常重要的一环。Python 提供了内置库 os
和 shutil
来对文件系统进行操作,然而相比传统的操作方法,最近开始流行的使用 pathlib
内置库的操作将会更加优雅。
当然,面对文件系统这样的庞然大物,再优雅的方法也显得比较臃肿。因此还请你耐心阅读这篇文档。
对于修改文件权限等高级的操作,还是需要使用 os
而不是 pathlib
进行操作,然而那不是我们计划在教程中探讨的。
创建路径对象
从函数获取特殊路径
pathlib
与 datetime
一样,是典型的面向对象设计思路,几乎所有的功能都是基于类和对象展开的。因此,获取一个路径对象非常重要。
先从最简单的获取当前程序运行目录开始:
import pathlib
a = pathlib.Path.cwd()
print(a)
print(type(a))
cmd 终端输出如下:

可见,它获取到了我们的工作目录(运行程序时使用的 cmd 目录),并作为字符串打印了出来。当然了,这个对象 a
并不是一个字符串那么简单,由打印出来的类型可知这是一个 WindowsPath
对象(pathlib
会自动识别操作系统并生成对应的路径对象)。
与之类似的,我们可以使用 pathlib.Path.home()
获取用户的家目录,输出:C:\Users\yxzlwz
。
根据路径字符串生成
再看看怎么根据路径字符串生成 Path
对象:
from pathlib import Path
print(__file__) # e:\Programming\Python\临时\main.py
print(Path(__file__)) # e:\Programming\Python\临时\main.py
print(Path('main copy.py')) # main copy.py
print(Path('main copy.py').resolve()) # E:\Programming\Python\临时\main copy.py
print(Path('D:/E:/file_that_do_not_exist.py')) # D:\E:\file_that_do_not_exist.py
相关信息
__file__
和 __name__
类似,是 Python 的内建变量。__file__
表示当前文件。
此处要注意两点:
- 使用
\
和/
表示路径均可,pathlib
会根据操作系统自动转换; - 任何传入的字符串都可以创建出对应的
Path
对象,pathlib
不会验证这个路径存不存在,甚至不会验证这个路径在当前操作系统下是否合法。
获取路径详情
先来看一看路径的组成:

相关信息
Linux 下我测试 anchor 和 drive 属性输出均为空,Windows 下可分别输出 e:\ 和 e:
我们使用 __file__
为例来演示。
from pathlib import Path
path = Path(__file__)
print(path.exists()) # 判断路径是否存在,输出:True
print(path.is_file()) # 判断路径是否为文件,输出:True
print(path.is_dir()) # 判断路径是否为目录,输出:False
print(path.drive, path.anchor, path.root) # (不常用)输出:e: e:\ \
print(path.name) # 获取文件名,输出:main.py
print(path.stem) # 获取文件名(不包含后缀名),输出:main
print(path.suffix) # 获取文件后缀名,输出:.py
print(path.parent) # 获取父目录,输出:e:\Programming\Python\临时
print(list(path.parents)) # 获取每一级父目录,输出:[WindowsPath('e:/Programming/Python/临时'), WindowsPath('e:/Programming/Python'), WindowsPath('e:/Programming'), WindowsPath('e:/')]
获取路径对应的文件详情
from pathlib import Path
path = Path(__file__)
print(path.stat()) # os.stat_result(st_mode=33206, st_ino=3377699720529488, st_dev=444659244, st_nlink=1, st_uid=0, st_gid=0, st_size=71, st_atime=1659769391, st_mtime=1659769391, st_ctime=1654827238)
print(path.stat().st_size) # 71
print(path.stat().st_mtime) # 1659769391
... # 对应第五行元组的任意一项均可取出
print(Path('file_that_do_not_exist').stat()) # 抛出 FileNotFoundError 异常:获取文件信息时文件必须存在
操作文件内容
Path
对象可以直接作为路径传递给 open
函数:
from pathlib import Path
path = Path('file.txt')
with open(path, 'w') as f:
# with open('file.txt', 'w') as f: # 等价操作
# with path.open('w') as f: # 等价操作
f.write('Hello World!')
我们也可以绕过 open
函数直接操作:
from pathlib import Path
path = Path('file.txt')
print(path.read_text()) # Hello World!
print(path.read_text(encoding='utf-8')) # Hello World!
print(path.read_bytes()) # b'Hello World!'
path.write_text('See you later!')
path.write_bytes(b'See you later!')
注意:
write_text
和write_bytes
使用的打开方式分别为 w 和 wb,书写前会清空原有内容;- 上面列出的每次操作都会重新打开和关闭文件,不建议在密集操作中使用。
目录操作
from pathlib import Path
path1 = Path('1/')
path1.mkdir()
path2 = Path('2/3/')
path2.mkdir(parents=True) # 创建多级目录需要parents=True
path1.mkdir(exist_ok=True) # exist_ok=True表示如果目录已存在不报错,否则抛出FileExistsError异常
path1.rename('1.5') # 重命名目录
path1.replace('1.5') # 移动目录
path1.rmdir() # 删除目录,要求目录为空
对于 rename
和 replace
两个函数,其实都可以完成重命名或移动操作。
事实上,它们在 Linux 上表现是一样的。区别在于在 Windows 上,调用前者如果存在了同名文件会报错,调用后者则会直接覆盖。因此,如果你希望操作在不同操作系统上具有相同表现,则使用 replace
;如果你更在意文件安全性,请使用 rename
。
列出目录下的文件
from pathlib import Path
path = Path('.')
print(list(path.iterdir())) # [WindowsPath('file.json'), WindowsPath('main copy.py'), WindowsPath('main.py'), WindowsPath('__pycache__')]
print(list(path.glob('*.py'))) # [WindowsPath('main copy.py'), WindowsPath('main.py')]
print(list(path.glob('main*'))) # [WindowsPath('main copy.py'), WindowsPath('main.py')]
print(list(path.glob('*.*'))) # [WindowsPath('file.json'), WindowsPath('main copy.py'), WindowsPath('main.py')]
文件操作
from pathlib import Path
path = Path('file.txt')
new_path = path.rename('new_file.txt')
print(new_path) # new_file.txt
print(path) # file.txt(调用 rename 和 replace 方法后不会更新当前对象)
new_path.replace(path)
new_path.unlink() # 删除文件
rename
和 replace
的区别和“目录操作”部分的说明相同。
还有一些更优雅的方式来创建新路径,以进行文件的重命名操作:
from pathlib import Path
path = Path('file.txt')
print(path) # file.txt
new_path = path.with_suffix('.json') # 类似地,有 with_name 和 with_suffix
print(new_path) # file.json
path.replace(new_path)
神奇的语法糖
>>> from pathlib import Path
>>> path = Path('E:/Programmig/Python/临时')
>>> path
WindowsPath('E:/Programmig/Python/临时')
>>> path / '1.txt'
WindowsPath('E:/Programmig/Python/临时/1.txt')
>>> path / '../1.txt'
WindowsPath('E:/Programmig/Python/临时/../1.txt')
>>> (path / '../1.txt').resolve()
WindowsPath('E:/Programmig/Python/1.txt')
版权所有
版权归属:异想之旅