如何使用Python读取一个10GB的文本文件?
中等Python
答题要点
# 错误:一次性读取 (MemoryError)
# with open('large.txt') as f:
# content = f.read()
# 正确 1: 逐行读取 (迭代器)
with open('large.txt', 'r') as f:
for line in f:
process(line)
# 正确 2: 块读取 (二进制或固定大小)
def read_in_chunks(file_object, chunk_size=1024):
while True:
data = file_object.read(chunk_size)
if not data:
break
yield data
with open('large_binary.dat', 'rb') as f:
for chunk in read_in_chunks(f):
process(chunk)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题