python中12个文件处理高效技巧,不允许你还不知道
在Python中高效处理文件是日常开发中的核心技能,尤其是处理大文件或需要高性能的场景。以下是经过实战验证的高效文件处理技巧,涵盖多种常见场景:
一、基础高效操作
1.始终使用上下文管理器(with语句)
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read() # 自动关闭文件,避免资源泄漏
2.逐行读取大文件(内存友好)
with open('large_file.log', 'r') as f:
for line in f: # 迭代器逐行读取,不加载整个文件到内存
process(line)
3.批量写入(减少I/O操作)
lines = [f"Line {i}\n" for i in range(10_000)]
with open('output.txt', 'w') as f:
f.writelines(lines) # 比循环写入快10倍以上
二、高级优化技巧
4.内存映射(mmap)处理超大文件
import mmap
with open('huge_data.bin', 'r+b') as f:
mm = mmap.mmap(f.fileno(), 0) # 映射整个文件
print(mm.find(b'\x00')) # 像操作内存一样搜索二进制数据
5.使用pathlib简化路径操作(Python 3.4+)
from pathlib import Path
# 读取和写入文件
Path('data.txt').write_text('Hello') # 一行代码完成写入
content = Path('data.txt').read_text() # 一行代码读取
6.二进制模式加速(非文本文件)
with open('image.jpg', 'rb') as f: # 'b'模式跳过编码解码
data = f.read() # 比文本模式快20%~30%
三、性能关键场景
7.生成器处理超大型文件
def read_large_file(file_path):
with open(file_path, 'r') as f:
yield from f # 生成器逐行返回,内存占用恒定
for line in read_large_file('10GB_file.txt'):
process(line)
8.多线程/异步IO(高并发场景)
- 线程池处理多个文件:
from concurrent.futures import ThreadPoolExecutor
def process_file(path):
with open(path) as f:
return len(f.read())
paths = ['file1.txt', 'file2.txt']
with ThreadPoolExecutor() as executor:
results = list(executor.map(process_file, paths))
异步IO(Python 3.7+):
import aiofiles
async def read_async():
async with aiofiles.open('data.txt', 'r') as f:
return await f.read()
9.高效CSV处理(用pandas或csv模块)
# pandas适合结构化数据处理(比原生csv模块快5~10倍)
import pandas as pd
df = pd.read_csv('large.csv', chunksize=10_000) # 分块读取
for chunk in df:
process(chunk)
四、避坑指南
10.避免这些低效操作
- 错误:重复打开同一文件
for _ in range(1000):
with open('data.txt') as f: # 频繁I/O开销
pass
正确:一次性读取后处理
with open('data.txt') as f:
data = f.read() # 单次I/O
for _ in range(1000):
process(data)
11.缓冲区大小优化(Linux/Windows差异)
with open('data.bin', 'rb', buffering=16*1024) as f: # 16KB缓冲区
data = f.read() # 减少系统调用次数
12.临时文件处理(tempfile模块)
import tempfile
with tempfile.NamedTemporaryFile(delete=True) as tmp:
tmp.write(b'Hello') # 自动销毁临时文件
tmp.seek(0)
print(tmp.read())
五、实战性能对比
方法 | 10MB文件读取时间 | 内存占用 |
f.read() | 0.02s | 10MB |
逐行迭代 | 0.05s | <1MB |
mmap | 0.01s | 虚拟内存映射 |
总结
- 小文件:直接read()/write()
- 中等文件:逐行迭代或分块处理
- 超大文件:mmap或生成器
- 结构化数据:优先用pandas
- 高并发:多线程/异步IO
掌握这些技巧后,你的文件处理性能可提升3~10倍,尤其是在处理GB级数据时效果显著。