5Python Cookbook(第3版)

文件与I/O

输入输出

文件读写CSV处理JSON二进制I/O

🎯 AI 时代的学习建议:不要只读理论。理解这一章的设计动机(为什么需要这个概念?)和边界条件(什么情况下会失效?)。当 AI 生成的代码涉及这些概念时,你能判断它是否用对了场景。AI 能帮你总结内容,但无法替代你亲手阅读、思考、建立直觉的过程。

第5章:文件与I/O

一、导读

1.1 本章学习目标

第5章讲解 Python 的文件和 I/O 操作:文件读写、CSV 处理、JSON 处理、二进制 I/O。

本章核心学习目标:

  • 掌握文件读写:open、read、write、上下文管理器
  • 理解 CSV 和 JSON 处理
  • 掌握二进制 I/O

1.2 为什么本章如此重要

文件 I/O 是程序与外部数据交互的基本方式。Python 提供了简洁而强大的文件操作接口。

1.3 核心问题引导

为什么应该总是用 with 语句打开文件?

如何处理大文件的逐行读取?

CSV 和 JSON 的处理有什么最佳实践?


二、核心概念详解

2.1 文件读写

python
# 文本文件
with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()      # 读取全部内容
    # lines = f.readlines()  # 读取所有行
    # for line in f:         # 逐行读取(推荐)
    #     print(line.strip())

# 写入
with open('output.txt', 'w', encoding='utf-8') as f:
    f.write("Hello\n")
    f.writelines(["Line 1\n", "Line 2\n"])

# 追加
with open('log.txt', 'a', encoding='utf-8') as f:
    f.write("New entry\n")

# 大文件逐行处理
def process_large_file(filename):
    with open(filename, 'r') as f:
        for line in f:
            yield line.strip()

2.2 CSV 处理

python
import csv

# 读取 CSV
with open('data.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['age'])

# 写入 CSV
data = [
    {'name': 'Alice', 'age': 30, 'city': 'NYC'},
    {'name': 'Bob', 'age': 25, 'city': 'LA'},
]
with open('output.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=['name', 'age', 'city'])
    writer.writeheader()
    writer.writerows(data)

2.3 JSON 处理

python
import json

# 序列化
data = {'name': 'Alice', 'age': 30, 'scores': [95, 87, 92]}
json_str = json.dumps(data, indent=2, ensure_ascii=False)
print(json_str)

# 反序列化
parsed = json.loads(json_str)
print(parsed['name'])

# 文件操作
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2)

with open('data.json', 'r') as f:
    loaded = json.load(f)

# 自定义序列化
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def user_to_dict(user):
    return {'name': user.name, 'age': user.age}

user = User("Alice", 30)
print(json.dumps(user, default=user_to_dict))

三、实战案例

3.1 案例一:CSV 数据清洗

python
import csv
from collections import defaultdict

def clean_csv(input_file, output_file):
    """清洗 CSV 数据:去除空行、标准化字段"""
    stats = defaultdict(int)
    
    with open(input_file, 'r') as fin, open(output_file, 'w', newline='') as fout:
        reader = csv.DictReader(fin)
        writer = csv.DictWriter(fout, fieldnames=reader.fieldnames)
        writer.writeheader()
        
        for row in reader:
            # 跳过空行
            if not any(row.values()):
                stats['empty'] += 1
                continue
            
            # 标准化字段
            cleaned = {}
            for key, value in row.items():
                cleaned[key] = value.strip() if value else ''
            
            writer.writerow(cleaned)
            stats['processed'] += 1
    
    print(f"Stats: {dict(stats)}")

四、本章小结

with 语句保证文件正确关闭

逐行读取适合处理大文件

csv 和 json 模块提供便捷的格式化支持


五、思考与练习

如何处理编码错误的文件?

如何实现文件的原子写入?


5/12文件与I
0%