python-28-python进阶pathlib替代os和os.path读写文件
一.简介
pathlib
是一个功能强大且简洁的模块,在python3.4版本以后被加入进来,主要的功能是
1.操作文件和目录路径
2.需要跨平台路径兼容
3.替代传统的os和os.path、open()
既然这么强大我们就来一步步解析pathlib并彻底掌握pathlib,好!来开始我们今天的日拱一卒!
二.pathlib 的核心是Path类
pathlib
的核心是 Path
类,用于创建和操作文件路径对象。
根据操作系统不同,Path
对象会自动使用适合的平台路径分隔符:
- Windows:
\
- POSIX(Linux/macOS):
/
三.pathlib常见的方法和用法
-
创建路径对象
from pathlib import Path # 相对路径 p1 = Path("example.txt") print(p1) # 输出: example.txt # 绝对路径 p2 = Path("/home/user/example.txt") print(p2) # 输出: /home/user/example.txt # 当前目录 p3 = Path.cwd() print(p3) # 输出: 当前工作目录
-
获取路径属性
p = Path("/home/user/example.txt") print(p.name) # 文件名: example.txt print(p.stem) # 文件名不含后缀: example print(p.suffix) # 后缀名: .txt print(p.parent) # 父目录: /home/user print(p.parts) # 路径分段: ('/', 'home', 'user', 'example.txt')
-
检查路径
p = Path("example.txt") print(p.exists()) # 检查路径是否存在 print(p.is_file()) # 是否是文件 print(p.is_dir()) # 是否是目录
-
创建和删除路径
# 创建文件
p = Path("new_file.txt")
p.touch() # 创建空文件
# 创建目录
d = Path("new_folder")
d.mkdir(parents=True, exist_ok=True) # 创建目录,包含父目录
# 删除文件或目录
p.unlink() # 删除文件
d.rmdir() # 删除目录(仅当目录为空)
-
路径拼接
base = Path("/home/user") new_path = base / "documents" / "file.txt" print(new_path) # 输出: /home/user/documents/file.txt
-
遍历目录
p = Path("/home/user") # 遍历文件和子目录 for item in p.iterdir(): print(item) # 遍历所有文件(递归) for file in p.rglob("*.txt"): print(file) # 输出所有 .txt 文件
-
文件操作,当文本文件读写 pathlib 默认使用的是UTF-8 编码
# 写入文件 p = Path("example.txt") p.write_text("Hello, World!") # 写入文本 p.write_bytes(b"Binary data") # 写入二进制数据 # 写入文件时指定编码 p.write_text("你好,世界", encoding="gbk") # 写入文件时指定字符编码 # 读取文件 print(p.read_text()) # 读取文本 print(p.read_bytes()) # 读取二进制数据 # 读取文件时指定编码 content = p.read_text(encoding="gbk") # 读取文件时指定字符编码 print(content)
-
文件系统操作
# 重命名 p = Path("example.txt") p.rename("new_example.txt") # 复制(需要 shutil 模块) from shutil import copy copy("source.txt", "destination.txt") # 当目标文件不存在则重命名文件,当目标文件存在则覆盖目标文件,且无提示 p.replace("new_location.txt") # 将文件移动到 /new/path/ 下 p = Path("example.txt") p.replace("/new/path/example.txt")
四.与 os
和 os.path
的对比
功能 | os / os.path | pathlib |
---|---|---|
路径操作 | 字符串操作,需手动拼接 | 面向对象,直接使用 / 操作符 |
平台兼容性 | 手动处理分隔符(os.sep ) | 自动处理分隔符 |
文件和目录检查 | os.path.exists() | Path.exists() |
创建目录或文件 | os.mkdir() | Path.mkdir() 和 Path.touch() |
文件读写 | open() | Path.write_text() / read_text() /write_bytes() /read_bytes() |
六.常见的应用案例:
-
批量处理文件
from pathlib import Path # 获取当前目录下的所有 .txt 文件 current_dir = Path(".") for file in current_dir.glob("*.txt"): print(file.name)
-
创建层级目录
from pathlib import Path # 创建嵌套目录 nested_dir = Path("project") / "src" / "tests" nested_dir.mkdir(parents=True, exist_ok=True)
-
自动备份文件
from pathlib import Path file_path = Path("example.txt") if file_path.exists(): backup_path = file_path.with_suffix(".bak") file_path.rename(backup_path) print(f"Backup created: {backup_path}")
七.总结
我记得我之前写文件读写等操作我写了9节,而Python pathlib库来操作文件是不是更简单,因为把文件变为一个对象来进行操作,但是要注意 想使用pathlib,python版本必须为3.4以上!
创作整理不易,请大家多多关注 多多点赞,有写的不对的地方欢迎大家补充,我来整理,再次感谢!