前言
Python 很适合写小工具,其中最常见的场景就是读写文件。
比如批量处理日志、整理 CSV、读取配置、生成简单报表。学会文件处理以后,Python 的实用性会明显提升。
这篇记录 Python 读写文本文件、使用 with、处理路径、读写 JSON,以及异常处理的基础。
打开文件
最基础的打开文件方式是 open。
file = open("demo.txt", "r", encoding="utf-8")
content = file.read()
file.close()
这段代码能工作,但不推荐这样写。因为如果 read 过程中出错,close 可能不会执行。
更推荐用 with:
with open("demo.txt", "r", encoding="utf-8") as file:
content = file.read()
with 会在代码块结束后自动关闭文件。写文件时也一样。
读取方式
read 会一次读取全部内容。
with open("demo.txt", "r", encoding="utf-8") as file:
content = file.read()
如果文件很大,一次读完可能占很多内存。可以逐行读取:
with open("demo.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
逐行处理日志文件时,这种方式更合适。
也可以用 readlines:
lines = file.readlines()
它会把所有行读成列表。文件不大时可以用,文件大时还是逐行更稳。
写文件
写文件用模式w。
with open("output.txt", "w", encoding="utf-8") as file:
file.write("hello\n")
注意,w会覆盖原文件。
如果想追加,用a:
with open("output.txt", "a", encoding="utf-8") as file:
file.write("new line\n")
写文件时一定要想清楚是覆盖还是追加。脚本处理数据时,误用覆盖可能会把原文件清掉。
pathlib 处理路径
Python 里处理路径,我更喜欢 pathlib。
from pathlib import Path
path = Path("data") / "demo.txt"
这比手写字符串拼接舒服,也更跨平台。
判断文件是否存在:
if path.exists():
print("exists")
创建目录:
output_dir = Path("output")
output_dir.mkdir(parents=True, exist_ok=True)
读写文件也可以用 Path 的方法:
content = path.read_text(encoding="utf-8")
path.write_text("hello", encoding="utf-8")
小脚本里这样写很简洁。
JSON 读写
Python 内置 json 模块。
读取 JSON:
import json
with open("user.json", "r", encoding="utf-8") as file:
user = json.load(file)
写 JSON:
with open("user.json", "w", encoding="utf-8") as file:
json.dump(user, file, ensure_ascii=False, indent=2)
ensure_ascii=False可以让中文正常写出,而不是变成转义字符。indent=2让文件更好看。
处理接口返回、配置文件、简单数据存储时,JSON 很常用。
异常处理
文件操作经常会出错。文件不存在、没有权限、编码不对、JSON 格式错误,都可能发生。
Python 用 try except 处理异常。
try:
content = Path("demo.txt").read_text(encoding="utf-8")
except FileNotFoundError:
print("文件不存在")
不要一上来就写:
except Exception:
pass
这会把错误吞掉,后面排查很痛苦。
更好的方式是捕获你能处理的异常,处理不了的让它暴露出来。
finally
finally 里的代码无论是否异常都会执行。
try:
print("do something")
finally:
print("clean up")
不过文件关闭这件事通常用 with 就够了,不需要自己写 finally。
finally 更适合释放某些资源、打印收尾日志、恢复临时状态。
小工具的结构
写文件处理脚本时,我喜欢拆成几个函数。
from pathlib import Path
def load_data(path: Path) -> list[str]:
return path.read_text(encoding="utf-8").splitlines()
def process(lines: list[str]) -> list[str]:
return [line.strip() for line in lines if line.strip()]
def save_data(path: Path, lines: list[str]) -> None:
path.write_text("\n".join(lines), encoding="utf-8")
这样比所有逻辑写在一起清楚。
文件路径、处理逻辑、输出逻辑分开,后面想改输入来源或输出格式也方便。
编码问题
中文环境里,编码问题很常见。
所以读写文本文件时,我建议明确写encoding="utf-8"。不要依赖系统默认编码。
如果遇到历史文件不是 UTF-8,要先确认实际编码,再转换。不要靠猜。
编码问题看起来小,但它很容易让脚本在自己电脑能跑,到别人电脑就报错。
小结
Python 文件处理很实用,掌握 open、with、pathlib、json 和异常处理以后,就能写很多小工具。
我的习惯是:文本读写明确编码,路径用 pathlib,文件关闭交给 with,异常只捕获能处理的类型,脚本逻辑拆成几个函数。
这些习惯不复杂,但能让小脚本从“能跑”变成“比较稳”。
気に入ったならばコメントを残してくださいね~