文件读写与 pathlib

Python 3 推荐使用 pathlib 模块处理文件路径,相比传统的 os.path 更加直观。

1. pathilib 基础

from pathlib import Path

# 创建路径对象
p = Path("my_folder/file.txt")

# 路径拼接
p = Path("my_folder") / "file.txt"

# 获取信息
p.name        # 'file.txt'        文件名
p.stem        # 'file'          无扩展名
p.suffix      # '.txt'         扩展名
p.parent      # my_folder      父目录
p.exists()    # True/False     是否存在
p.is_file()   # True/False    是否是文件
p.is_dir()    # True/False    是否是目录

2. 读取文件

方法一:read_text / read_bytes

from pathlib import Path

# 读取文本
content = Path("file.txt").read_text(encoding="utf-8")

# 读取二进制
data = Path("image.png").read_bytes()

# 读取行
lines = Path("file.txt").read_text().splitlines()

方法二:open 上下文管理器

from pathlib import Path

p = Path("file.txt")

# 读取全部
with p.open() as f:
    content = f.read()

# 读取一行
with p.open() as f:
    line = f.readline()

# 逐行读取
with p.open() as f:
    for line in f:
        print(line.rstrip())

# 读取所有行到列表
with p.open() as f:
    lines = f.readlines()

3. 写入文件

from pathlib import Path

p = Path("output.txt")

# 写入文本(覆盖)
p.write_text("Hello World", encoding="utf-8")

# 写入二进制
p.write_bytes(b"\x00\x01\x02")

# 追加写入
with p.open("a", encoding="utf-8") as f:
    f.write("\n新行")

4. 处理文件夹

from pathlib import Path

p = Path("my_folder")

# 创建文件夹
p.mkdir(exist_ok=True, parents=True)

# 删除文件夹(空目录)
p.rmdir()

# 列出文件
for item in p.iterdir():
    print(item.name)

# 递归列出
for item in p.rglob("*.txt"):
    print(item)

# glob 模式匹配
list(Path(".").glob("*.txt"))           # 当前目录的 .txt
list(Path(".").glob("**/*.py"))         # 所有子目录的 .py

5. 文件操作

from pathlib import Path

src = Path("source.txt")
dst = Path("dest.txt")

# 复制
import shutil
shutil.copy(src, dst)

# 移动
shutil.move(src, dst)

# 删除文件
dst.unlink()

# 重命名
src.rename("new_name.txt")

# 获取文件大小
src.stat().st_size

# 修改时间
import time
os.utime(src, (time.time(), time.time()))

6. 操作示例

批量重命名

from pathlib import Path

folder = Path("images")

for p in folder.glob("*.png"):
    new_name = p.stem.replace(" ", "_") + ".png"
    p.rename(p.parent / new_name)

查找大文件

from pathlib import Path

folder = Path(".")
large_files = []

for p in folder.rglob("*"):
    if p.is_file() and p.stat().st_size > 100_000_000:
        large_files.append((p.stat().st_size, p))

large_files.sort(reverse=True)
for size, p in large_files[:10]:
    print(f"{size:>10,} {p}")

与 os.path 对照

os.path pathlib
os.path.join(a, b) Path(a) / b
os.path.exists(p) Path(p).exists()
os.path.dirname(p) Path(p).parent
os.path.basename(p) Path(p).name
os.path.splitext(p) (Path(p).stem, Path(p).suffix)
os.listdir(p) list(Path(p).iterdir())
os.walk(p) Path(p).rglob("*")

pathlib 是现代 Python 推荐的路径处理方式,代码更简洁易读。