第八章:文件操作
读写文本文件
bash
# 使用 with 语句(推荐!自动关闭文件)
# 写入文件
with open("hello.txt", "w", encoding="utf-8") as f:
f.write("你好,Python!\n")
f.write("第二行内容\n")
f.write("第三行内容\n")
print("文件写入完成!")
# 读取整个文件
with open("hello.txt", "r", encoding="utf-8") as f:
content = f.read()
print(f"--- 文件全部内容 ---")
print(content)
# 逐行读取(适合大文件)
with open("hello.txt", "r", encoding="utf-8") as f:
print("--- 逐行读取 ---")
for line_num, line in enumerate(f, 1):
print(f"第{line_num}行:{line.strip()}")bash
文件写入完成!
--- 文件全部内容 ---
你好,Python!
第二行内容
第三行内容
--- 逐行读取 ---
第1行:你好,Python!
第2行:第二行内容
第3行:第三行内容📝 备注: 📝 文件打开模式:"r"只读(默认)、"w"写入(覆盖)、"a"追加、"r+"读写、"rb"二进制读取。
处理 JSON 文件
bash
import json
# Python 字典 → JSON 文件
data = {
"students": [
{"name": "小明", "age": 18, "scores": [85, 92, 78]},
{"name": "小红", "age": 17, "scores": [90, 95, 88]},
{"name": "小刚", "age": 19, "scores": [70, 65, 80]}
],
"class": "三年二班"
}
with open("students.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print("JSON 文件已保存!")
# JSON 文件 → Python 字典
with open("students.json", "r", encoding="utf-8") as f:
loaded = json.load(f)
for student in loaded["students"]:
avg = sum(student["scores"]) / len(student["scores"])
print(f" {student['name']}:平均分 {avg:.1f}")bash
JSON 文件已保存!
小明:平均分 85.0
小红:平均分 91.0
小刚:平均分 71.7处理 CSV 文件
bash
import csv
# 写入 CSV
with open("employees.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "部门", "工资"])
writer.writerow(["张三", "技术部", 15000])
writer.writerow(["李四", "市场部", 12000])
writer.writerow(["王五", "技术部", 18000])
# 读取 CSV
with open("employees.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
print("员工信息:")
for row in reader:
print(f" {row['姓名']} | {row['部门']} | {row['工资']}元")bash
员工信息:
张三 | 技术部 | 15000元
李四 | 市场部 | 12000元
王五 | 技术部 | 18000元