Pathlib返回的路径是WindowsPath或PosixPath。这个取决于我们的操作系统
Pathlib会自动调整路径的格式,从而让我们的代码platform-independent。
获取当前路径
Path.cwd()
串联路径
无论使用什么操作系统,都使用forward-slash来串联路径
from pathlib import Path
for the_file in Path.cwd().glob("*.pdf")
new_path = Path("/data/archive") /the_file.name
the_file.rename(new_path)
等效于.joinpath()函数
针对path对象的常见操作
.name获取文件名,不包含路径.stem文件名称,不包含扩展名.suffix只有扩展名.anchor根路径.parent父对象- 返回的object还可以使用获取其parent属性
文件操作
打开,读取,写
path.open
.read_text(encoding = "utf-8") 按照指定编码方式读取path对象的文本内容
.write_text() 也可以指定编码格式
重命名
- with_stem
- with_suffix
- with_name
- 重命名文件后的path-object
- 但是需要使用replace执行重命名操作
拷贝文件
from pathlib import Path
original_file = Path("test_1.txt")
new_file = original_file.with_stem("test_2")
new_file.write_bytes(original_file.read_bytes())
移动文件
- write_bytes
- unlink
创建空文件
- exists
- touch
iterator
- iterdir()
- glob
- rglob
- relative_to
- parts 拆分路径为多个组分
- .stat().st_mtime