文本读写
from pathlib import Path p = Path("example.txt") p.write_text("你好,世界", encoding="utf-8") content = p.read_text(encoding="utf-8")
二进制读写
data = b"\x00\x01\x02" with open("data.bin", "wb") as f: f.write(data) with open("data.bin", "rb") as f: raw = f.read()
pathlib 常用操作
from pathlib import Path root = Path(".") py_files = list(root.rglob("*.py")) new_dir = Path("output") new_dir.mkdir(exist_ok=True)
转载请注明:周志洋的博客 » Python实用技巧-文件读写与pathlib