Python 文件操作
1. 文件操作基础
1.1 文件打开模式
Python 提供了多种文件打开模式:
r: 只读模式(默认)w: 写入模式(会覆盖原有内容)a: 追加模式b: 二进制模式t: 文本模式(默认)+: 读写模式
1.2 基本文件操作
# 打开文件
file = open('example.txt', 'r')
# 读取文件内容
content = file.read() # 读取整个文件
line = file.readline() # 读取一行
lines = file.readlines() # 读取所有行到列表
# 写入文件
file.write('Hello, World!')
file.writelines(['line1\n', 'line2\n'])
# 关闭文件
file.close()
2. 使用 with 语句
推荐使用 with 语句进行文件操作,它能自动处理文件的关闭:
with open('example.txt', 'r') as file:
content = file.read()
# 文件会在 with 块结束时自动关闭
3. 文件路径操作
3.1 使用 os 模块
import os
# 获取当前工作目录
current_dir = os.getcwd()
# 路径拼接
file_path = os.path.join('folder', 'subfolder', 'file.txt')
# 检查文件是否存在
if os.path.exists(file_path):
print('文件存在')
# 获取文件信息
file_size = os.path.getsize(file_path)
3.2 使用 pathlib 模块(Python 3.4+)
from pathlib import Path
# 创建路径对象
path = Path('folder/file.txt')
# 检查文件是否存在
if path.exists():
print('文件存在')
# 读取文件
content = path.read_text()
4. 文件编码
4.1 指定编码
# 使用 UTF-8 编码打开文件
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
# 写入时指定编码
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('你好,世界!')
5. 文件操作最佳实践
- 始终使用
with语句处理文件 - 明确指定文件编码
- 处理文件操作异常
try:
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
except FileNotFoundError:
print('文件不存在')
except IOError:
print('文件读写错误')
6. 文件迭代
6.1 逐行读取
with open('large_file.txt', 'r') as file:
for line in file:
print(line.strip())
6.2 使用生成器处理大文件
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
# 使用生成器
for line in read_large_file('large_file.txt'):
process_line(line)
7. 临时文件操作
import tempfile
# 创建临时文件
with tempfile.NamedTemporaryFile() as temp_file:
temp_file.write(b'Hello, World!')
temp_file.flush()
# 临时文件会在 with 块结束时自动删除
8. 文件压缩和解压缩
8.1 ZIP 文件操作
import zipfile
# 创建 ZIP 文件
with zipfile.ZipFile('archive.zip', 'w') as zipf:
zipf.write('file1.txt')
zipf.write('file2.txt')
# 解压 ZIP 文件
with zipfile.ZipFile('archive.zip', 'r') as zipf:
zipf.extractall('extracted_files')
9. 文件监控
import time
from pathlib import Path
def watch_file(file_path):
path = Path(file_path)
last_modified = path.stat().st_mtime
while True:
time.sleep(1)
current_modified = path.stat().st_mtime
if current_modified != last_modified:
print(f'文件 {file_path} 已被修改')
last_modified = current_modified
10. 总结
Python 提供了丰富的文件操作功能,从基本的读写操作到高级的文件管理功能。在实际应用中,应该:
- 优先使用
with语句进行文件操作 - 正确处理文件编码
- 适当处理异常情况
- 对于大文件,使用迭代方式处理
- 注意文件资源的及时释放
- 使用适当的文件操作模式
- 遵循最佳实践确保代码的可维护性和安全性
