如何用Python高效处理超大文件?
进阶Python
答题要点
import mmap
import os
# 内存映射读取
def search_in_large_file(filepath, pattern):
with open(filepath, 'rb') as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
index = mm.find(pattern.encode())
if index != -1:
mm.seek(index)
return mm.readline()
# 分块处理大文件
def process_large_file(filepath, chunk_size=1024*1024*100): # 100MB
with open(filepath, 'rb') as f:
while True:
chunk = f.read(chunk_size)
if not chunk:
break
process_chunk(chunk)
# 逐行处理(内存高效)
def process_line_by_line(filepath):
with open(filepath, 'r', buffering=1024*1024) as f:
for line in f:
process_line(line)
# 多进程并行处理
import multiprocessing as mp
def parallel_process(filepath, num_workers=4):
file_size = os.path.getsize(filepath)
chunk_size = file_size // num_workers
with mp.Pool(num_workers) as pool:
args = [(filepath, i*chunk_size, chunk_size)
for i in range(num_workers)]
results = pool.starmap(process_chunk_at_offset, args)
return merge_results(results)
def process_chunk_at_offset(filepath, offset, size):
with open(filepath, 'r') as f:
f.seek(offset)
if offset > 0:
f.readline() # 跳到下一行开始
content = f.read(size)
# 处理content
return result
# pandas分块读取
for chunk in pd.read_csv('huge.csv', chunksize=100000):
process(chunk)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题