我有一个大的文本文件(约7GB)。 我正在寻找最快的方式来读取大型文本文件。 我一直在研究使用多种方法,例如按块读取以加快进程。
例如,在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行文本。
其他作者建议使用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
行为一组分块读取文件。