我有一个大文本文件 (~7 GB)。我正在寻找是否存在读取大文本文件的最快方法。我一直在阅读有关使用多种方法逐 block 读取以加快进程的信息。
例如 effbot建议
# File: readline-example-3.py
file = open("sample.txt")
while 1:
lines = file.readlines(100000)
if not lines:
break
for line in lines:
pass # do something**strong text**
为了每秒处理 96,900 行文本。 其他 authors建议使用 islice()
from itertools import islice
with open(...) as f:
while True:
next_n_lines = list(islice(f, n))
if not next_n_lines:
break
# process next_n_lines
list(islice(f, n))
将返回文件 f
的下 n
行的列表。在循环中使用它会给你提供 n
行
最佳答案
with open(<FILE>) as FileObj:
for lines in FileObj:
print lines # or do some other thing with the line...
每次将一行读入内存,完成后关闭文件...
关于Python 读取大型文本文件(几 GB)的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14944183/