之前就听说过 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 — 面向对象的文件系统路径 官方文档。