适用对象:需要做数据转换、文件批处理、自动化报表的开发者
阅读时长:约 7 分钟
关联练习:pe081-090
环境要求:Python 3.14+、Jupyter 1.1+、Notebook 7.5+、nbconvert 7.17+
一句话核心
with 一行打开多文件 + for line in f 逐行处理 + f"{x},{y}\\n" 写回,这就是 ETL 的核心套路。
一、同时打开读文件和写文件
核心: 用逗号分隔多个 open,统一 with 管理。
# 一次打开两个文件:读 + 写
with open("input.txt") as fin, \\
open("output.txt", "w") as fout:
for line in fin:
# 处理逻辑
fout.write(line)
要点:
- 自动 close 所有文件,即使中间报错
- 读用 "r",写覆盖用 "w",追加用 "a"
- 写完必须 fout.close()(或用 with),否则内容可能丢失
二、读写模式对照
| r | 只读 | 报错 | – |
| w | 写入 | 创建 | 是 |
| a | 追加 | 创建 | 否 |
| r+ | 读写 | 报错 | – |
| b | 二进制 | – | – |
w 模式警告: 每次打开都会清空原文件,数据丢失风险大。
三、实战:数据转换写回文件
with open("input.csv") as fin, \\
open("output.csv", "w") as fout:
for line in fin:
# 首行是表头,原样写入
if "x,y" in line:
fout.write(line)
else:
# 数据行:x,y → x*5, y*5
x, y = line.strip().split(",")
x = int(x) * 5
y = int(y) * 5
fout.write(f"{x},{y}\\n")
关键步骤:
四、CSV 数据统计函数
def compute_score():
"""计算文件中所有分数的最大/最小/平均值"""
scores = []
with open("scores.txt", encoding="utf-8") as fin:
for line in fin:
line = line.strip()
fields = line.split(",") # 只支持英文逗号
scores.append(int(fields[–1])) # 取每行最后一个字段
max_score = max(scores)
min_score = min(scores)
avg_score = round(sum(scores) / len(scores), 2)
return max_score, min_score, avg_score # 元组多返回值
# 元组解包
max_score, min_score, avg_score = compute_score()
print(f"最高: {max_score}, 最低: {min_score}, 平均: {avg_score}")
# 最高: 99, 最低: 55, 平均: 80.0
核心 API:
- max() / min() / sum() / len():内置统计
- round(x, 2):保留 2 位小数
- 元组解包:a, b, c = func()
五、字符编码
核心: 处理中文必须显式指定 encoding="utf-8"。
# 写文件
with open("out.txt", "w", encoding="utf-8") as f:
f.write("你好,Python")
# 读文件
with open("in.txt", "r", encoding="utf-8") as f:
content = f.read()
Windows 默认编码: GBK(cp936),跨平台或中文文件务必用 UTF-8。
查看文件编码(常用方法):
import chardet # 第三方库
with open("file.txt", "rb") as f:
raw = f.read()
print(chardet.detect(raw)) # {'encoding': 'UTF-8', 'confidence': 0.99}
六、文本 vs 二进制读写
# 文本模式
with open("text.txt", "r", encoding="utf-8") as f:
text = f.read() # str 类型
# 二进制模式(图片、视频、压缩包)
with open("image.jpg", "rb") as f:
data = f.read() # bytes 类型
关键区别:
- 文本模式需要 encoding,返回 str
- 二进制模式无 encoding,返回 bytes
- 网络下载文件必须用 "wb" 写入
七、文件指针操作
with open("file.txt", "r") as f:
f.seek(0) # 指针移到开头
f.seek(10) # 移到第 10 字节
f.tell() # 返回当前指针位置
f.read(5) # 读 5 个字符
典型用途: 大文件分块读取、日志文件定位。
八、实战:数据清洗流程
def clean_data(input_path, output_path):
"""把脏数据(空行/注释行)过滤后写入新文件"""
with open(input_path, encoding="utf-8") as fin, \\
open(output_path, "w", encoding="utf-8") as fout:
for line in fin:
stripped = line.strip()
# 跳过空行和注释行
if not stripped or stripped.startswith("#"):
continue
fout.write(stripped + "\\n")
这是一个迷你版 ETL:
- Extract:读源文件
- Transform:过滤/转换
- Load:写目标文件
实践清单
- 写脚本统计 CSV 文件每列的最大值
- 把一个日志文件按关键字过滤后输出
- 实现"读 A 文件,转大写,写 B 文件"的功能
- 用 try-except 包装文件操作,处理文件不存在的情况
常见问题 FAQ
Q1:with 比 f = open() 好在哪?
A:with 通过上下文管理器保证文件一定关闭,即使中途异常。这是 Python 推荐做法。
Q2:读文件遇到 UnicodeDecodeError 怎么办?
A:1)确认文件实际编码;2)用 errors="ignore" 跳过坏字节;3)chardet 库自动检测。
Q3:f.read() / f.readline() / f.readlines() 区别?
A:
- read():一次读全部
- readline():读一行
- readlines():读所有行到列表
大文件优先用 for line in f 逐行处理,内存友好。
相关资源
- Python 官方 – 文件读写
- Python 官方 – open 内置函数
网络取材来源于:ant-python-exercises-100p:蚂蚁学 python 社区,python 编程练习题 100 题
网硕互联帮助中心




评论前必须登录!
注册