【python】比起os.path,Pathlib太方便了

简介

这次要介绍的是Python的标准库pathlib。 (第N次……)
老实说,这个标题有点夸张,但是pathlib比os.path更方便,不妨一试!

什么是pathlib?

pathlib 是一个用于处理文件路径的库。
通过pathlib,可以将文件路径视为对象而不是字符串。

os.path 还不够吗?

pathlib 相对 os.path 有以下优点:

  • 丰富的方法
    pathlib 将文件路径视为对象,因此可以对文件路径执行各种操作。
  • 接纳了路径分隔符的差异。
    pathlib 接纳因操作系统而异的路径分隔符。
    例如,Windows 使用 \,Linux 使用 /,若使用 pathlib,则可以在任一操作系统上运行相同的代码。
  • 易于组合路径
    pathlib 可以使用 / 运算符组合路径。
    例如,使用 / 运算符组合 /home/user 和 /home/user/test.txt 会生成 /home/user/test.txt。

主要类型

在这里插入图片描述从这里引用
基本上,使用Path类首先了解该类的结构,这样当该类出现时就不会感到困惑。

  • PurePath
    用于表达与OS(操作系统)无关的路径的类

  • PurePosixPath
    用于表示 Linux 和 MacOS 路径的类

  • PureWindowsPath
    用于表示 Windows 路径的类

  • Path
    用于表示 Windows 路径的类

  • WindowsPath,PosixPath
    继承自Path的类,在Path中添加依赖于操作系统的文件系统操作。
    父类是独立于操作系统的 PureWindowsPath、PurePosixPath 和 Path

立即试用

生成路径

pathlib 使用 Path 类来生成路径。

from pathlib import Path

# 绝对路径
path = Path("/home/user/test.txt")

# 如果并排写,将被合并。
path = Path("/home", "user", "test.txt") # /home/user/test.txt

# 但请注意,如果并排写入两个或多个绝对路径,则先写入的路径将被忽略。
path = Path("/home", "/user", "test.txt") # /user/test.txt

# 想对路径
path = Path("test.txt")
# 当前目录
path = Path.cwd()

连接路径

可以使用 / 运算符组合路径。
(第一次看到的时候就被震撼了,因为太方便了……)

from pathlib import Path

# Path对象 + Path对象
path = Path("/home/user") / Path("test.txt")
# Path对象+字符串
path = Path("/home/user") / "test.txt"
# joinpath方法
path = Path("/home/user").joinpath("test.txt")

# 結合結果
print(path)  # /home/user/test.txt

路径分解

from pathlib import Path

path = Path("/home/user/test.txt")

# 目录名
print(path.parent)  # /home/user
# 文件名和扩展名
print(path.name)  # test.txt
# 文件名(没扩展名)
print(path.stem)  # test
# 扩展名
print(path.suffix)  # .txt

请注意,path.suffix 不支持像 tar.gz 这样的多个扩展名,因此必须使用 path.name 自行处理。

检查路径是否存在

就像 os.path.exists 一样,可以使用 path.exists 检查路径是否存在。

from pathlib import Path

path = Path("/home/user/test.txt")

# 路径是否存在
print(path.exists())  # True
# 路径是文件吗?
print(path.is_file())  # True
# 路径是目录吗?
print(path.is_dir())  # False

转换相对路径和绝对路径

可以使用 Path.relative_to(<相对引用路径>) 将绝对路径转换为相对路径。
可以使用== Path.absolute()== 将相对路径转换为绝对路径。
Path.resolve() 可以解析包含 … 或 . 的路径。

路径的处理

pathlib 允许对路径执行各种操作。

from pathlib import Path

path = Path("/home/user/test.txt")

# 移动/重命名路径(不覆盖)
path.rename("/home/user/test2.txt")
# 移动/重命名路径(覆盖)
path.replace("/home/user/test2.txt")
# 创建路径
path.mkdir() # 也可以使用parents=True来创建父目录
# 删除路径
path.rmdir()

文件操作

pathlib 可对文件执行各种操作。

from pathlib import Path

path = Path("/home/user/test.txt")

# 加载文件
path.read_text()
# 写入文件
path.write_text("Hello World!")
# 删除文件
path.unlink() # rmdir() 用于目录

加载json的例子

from pathlib import Path
import json

# 加载文件
path = Path("/home/user/test.json")
data = json.loads(path.read_text())
# 写入文件
path.write_text(json.dumps(data))

使用pathlib来写比使用open()更简洁。
特别是不必编写关闭文件的过程,这简化了代码。

获取信息

from pathlib import Path

fpath = Path("/home/user/test.txt")

# 文件大小
print(fpath.stat().st_size)  # 11
# 文件修改日期和时间
print(fpath.stat().st_mtime)  # 1620000000.0
# 文件创建日期和时间
print(fpath.stat().st_ctime)  # 1620000000.0

dpath = Path("/home/user")

# 获取目录内容
print(list(dpath.iterdir()))  # [PosixPath('/home/user/test.txt')]
# 递归获取目录内容
print(list(dpath.glob("**/*")))  # [PosixPath('/home/user/test.txt')]
# 递归获取文件
print(list(dpath.glob("**/*.txt")))  # [PosixPath('/home/user/test.txt')]

总结

在处理复杂的文件结构时,pathlib 总是派上用场。你觉得呢?
请尝试使用它,祝您Python生活愉快!

猜你喜欢

转载自blog.csdn.net/Allan_lam/article/details/134989411