文件读写基础
从文本文件开始 —— 持久化数据的第一步
为什么需要文件操作?
- 保存数据分析结果
- 读取外部数据
- 生成报告
- 数据备份
基本文件操作
1. 写入文件
python
# 写入文本文件
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("这是第一行\n")
f.write("这是第二行\n")
# 追加内容
with open('output.txt', 'a', encoding='utf-8') as f:
f.write("这是追加的内容\n")模式说明:
'r': 只读(默认)'w': 写入(覆盖)'a': 追加'r+': 读写
2. 读取文件
python
# 方法 1:一次读取全部
with open('output.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# 方法 2:按行读取
with open('output.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip()) # strip() 去除换行符
# 方法 3:读取所有行到列表
with open('output.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(lines) # ['第一行\n', '第二行\n', ...]3. 上下文管理器(with 语句)
python
# 不推荐(需要手动关闭)
f = open('file.txt', 'r')
content = f.read()
f.close()
# 推荐(自动关闭)
with open('file.txt', 'r') as f:
content = f.read()
# 离开 with 块后自动关闭文件实战案例
案例 1:保存问卷结果
python
respondents = [
{'id': 1001, 'age': 25, 'income': 50000},
{'id': 1002, 'age': 30, 'income': 75000},
{'id': 1003, 'age': 35, 'income': 85000}
]
# 保存为文本文件
with open('survey_results.txt', 'w', encoding='utf-8') as f:
f.write("问卷调查结果\n")
f.write("=" * 40 + "\n")
for resp in respondents:
line = f"ID:{resp['id']}, 年龄:{resp['age']}, 收入:{resp['income']}\n"
f.write(line)
print("结果已保存到 survey_results.txt")案例 2:读取并处理数据
python
# 读取数据文件
ages = []
with open('ages.txt', 'r') as f:
for line in f:
age = int(line.strip())
ages.append(age)
# 统计
print(f"平均年龄: {sum(ages) / len(ages):.1f}")
print(f"最大年龄: {max(ages)}")
print(f"最小年龄: {min(ages)}")案例 3:日志记录
python
from datetime import datetime
def log_analysis(message):
"""记录分析日志"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open('analysis.log', 'a', encoding='utf-8') as f:
f.write(f"[{timestamp}] {message}\n")
# 使用
log_analysis("开始数据清洗")
log_analysis("删除了 15 个异常值")
log_analysis("数据清洗完成")路径操作
使用 pathlib(推荐)
python
from pathlib import Path
# 创建路径对象
data_dir = Path('data')
raw_dir = data_dir / 'raw' # 路径拼接
processed_dir = data_dir / 'processed'
# 创建目录
raw_dir.mkdir(parents=True, exist_ok=True)
# 检查文件是否存在
file_path = raw_dir / 'survey.txt'
if file_path.exists():
print("文件存在")
# 列出目录中的文件
for file in data_dir.glob('*.txt'):
print(file.name)使用 os.path(传统方式)
python
import os
# 拼接路径
file_path = os.path.join('data', 'raw', 'survey.txt')
# 检查存在
if os.path.exists(file_path):
print("文件存在")
# 创建目录
os.makedirs('data/processed', exist_ok=True)
# 列出文件
files = os.listdir('data')最佳实践
1. 始终指定编码
python
# 明确指定 UTF-8
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()2. 使用 with 语句
python
# 自动关闭文件
with open('file.txt', 'r') as f:
content = f.read()3. 处理文件不存在的情况
python
from pathlib import Path
file_path = Path('data.txt')
if file_path.exists():
with open(file_path, 'r') as f:
content = f.read()
else:
print("文件不存在")练习题
python
# 练习 1:创建学生成绩文件
# 将以下数据写入 scores.txt
scores = [
('Alice', 85),
('Bob', 92),
('Carol', 78)
]
# 格式:Alice: 85
# 练习 2:统计文本文件
# 读取文件,统计:
# - 总行数
# - 总字符数
# - 包含特定关键词的行数下一步
下一节我们将学习 CSV 和 Excel 文件处理。
继续!