0%

是时候从 os.path 转向 pathlib 了

之前就听说过 pathlib 这个库,是从 3.4 加入的,由于习惯了 os 的相关操作,一直没有改,今天又查了一下,觉得还是转了,毕竟 pathlib 相关操作确实简单一些。

1
2
import os
from pathlib import Path
  • 判断某路径是否存在
1
2
os.path.exists("foo/tmp.txt")
Path("foo/tmp.txt").exists()
  • 创建文件夹
1
2
3
4
5
6
if not os.path.exists("foo"):
os.mkdir("foo")

p = Path("foo")
if not p.exists():
p.mkdir()
  • 遍历文件夹
1
2
3
4
5
6
7
8
9
10
for file in os.listdir("foo"):
print(file)

p = Path("foo")
for file in p.iterdir():
print(file)

# 根据所给的通配符遍历
for file in p.glob("*(2)*"):
print(file)
  • 判断是文件/文件夹
1
2
3
4
5
os.path.isdir("foo")
Path("foo").is_dir()

os.path.isfile("foo")
Path("foo").is_file()
  • 创建空文件

这个 touch 是不是很熟悉?

1
2
3
p = Path("foo/tmp.txt")
if not p.exists():
p.touch()
  • 打开文件
1
2
3
p = Path("foo/tmp.txt")
with p.open(encoding="utf-8") as f:
f.read()

还有很多好用的方法,具体可以看 pathlib — 面向对象的文件系统路径 官方文档。

Welcome to my other publishing channels