核心文件操作概览
1. 基础文件打开与关闭
# 基本语法
file = open('filename.txt', 'r', encoding='utf-8')
# ... 执行操作 ...
file.close()
推荐做法:使用 with 语句(上下文管理器)
# 自动处理文件关闭,即使发生异常也能保证资源释放
with open('filename.txt', 'r', encoding='utf-8') as file:
content = file.read()
常见打开模式:
| 模式 | 描述 |
|---|---|
'r' |
只读(默认) |
'w' |
只写(会覆盖已有文件,文件不存在则创建) |
'a' |
追加(在文件末尾写入,文件不存在则创建) |
'r+' |
读写(文件必须存在) |
'w+' |
读写(会覆盖已有文件) |
'a+' |
读写追加 |
'b' |
二进制模式(如 'rb', 'wb') |
2. 读取文件内容
with open('file.txt', 'r', encoding='utf-8') as f:
# 读取全部内容
content = f.read()
# 读取一行
line = f.readline()
# 读取所有行,返回列表
lines = f.readlines()
# 逐行遍历(推荐,内存友好)
for line in f:
print(line.strip()) # strip() 去除换行符
3. 写入文件内容
# 覆盖写入
with open('file.txt', 'w', encoding='utf-8') as f:
f.write('Hello, World!\n')
f.write('第二行内容')
# 追加写入
with open('file.txt', 'a', encoding='utf-8') as f:
f.write('\n这是追加的内容')
# 写入多行(列表)
lines = ['第一行\n', '第二行\n', '第三行\n']
with open('file.txt', 'w', encoding='utf-8') as f:
f.writelines(lines)
4. 文件指针操作
with open('file.txt', 'r', encoding='utf-8') as f:
# 获取当前位置
print(f.tell()) # 输出:0
# 移动指针
f.seek(10) # 移动到第 10 个字节
content = f.read(5) # 读取 5 个字符
5. 文件与目录操作(os 和 pathlib 模块)
传统 os 模块:
import os
# 检查文件是否存在
if os.path.exists('file.txt'):
print('文件存在')
# 获取文件大小
size = os.path.getsize('file.txt')
# 创建目录
os.makedirs('new_folder', exist_ok=True)
# 删除文件
os.remove('file.txt')
# 重命名文件
os.rename('old.txt', 'new.txt')
# 遍历目录
for filename in os.listdir('.'):
print(filename)
现代 pathlib 模块(推荐):
from pathlib import Path
# 创建 Path 对象
file_path = Path('file.txt')
# 检查文件是否存在
if file_path.exists():
print('文件存在')
# 读取文件
content = file_path.read_text(encoding='utf-8')
# 写入文件
file_path.write_text('新内容', encoding='utf-8')
# 创建目录
Path('new_folder').mkdir(parents=True, exist_ok=True)
# 获取文件信息
print(file_path.stat().st_size) # 文件大小
6. 常见实战场景
CSV 文件处理:
import csv
# 读取 CSV
with open('data.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# 写入 CSV
with open('data.csv', 'w', encoding='utf-8', newline='') as f:
writer = csv.writer(f)
writer.writerow(['姓名', '年龄', '城市'])
writer.writerow(['张三', 25, '北京'])
JSON 文件处理:
import json
# 读取 JSON
with open('data.json', 'r', encoding='utf-8') as f:
data = json.load(f)
# 写入 JSON
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
异常处理最佳实践:
try:
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
except FileNotFoundError:
print('文件不存在')
except PermissionError:
print('没有权限访问文件')
except UnicodeDecodeError:
print('文件编码格式错误')
关键要点总结
- 始终使用
with语句:避免忘记关闭文件导致资源泄漏 - 明确指定编码 :建议统一使用
encoding='utf-8' - 大文件用逐行读取:避免内存溢出
- 优先使用
pathlib:面向对象的路径操作更直观 - 做好异常处理:文件操作容易出现各种异常