Pathlib学习

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对象的常见操作

  1. .name 获取文件名,不包含路径
  2. .stem 文件名称,不包含扩展名
  3. .suffix 只有扩展名
  4. .anchor 根路径
  5. .parent 父对象
    1. 返回的object还可以使用获取其parent属性

文件操作

打开,读取,写

path.open

.read_text(encoding = "utf-8") 按照指定编码方式读取path对象的文本内容

.write_text() 也可以指定编码格式

重命名

  1. with_stem
  2. with_suffix
  3. with_name
    1. 重命名文件后的path-object
    2. 但是需要使用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())

移动文件

  1. write_bytes
  2. unlink

创建空文件

  1. exists
  2. touch

iterator

  1. iterdir()
  2. glob
  3. rglob
  4. relative_to
  5. parts 拆分路径为多个组分
  6. .stat().st_mtime