我有一个很大的文本文件(~7 GB)。我正在寻找是否存在读取大型文本文件的最快方法。我一直在读一些关于使用几种方法来逐块读取以加快进程的文章。
在示例中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
行的形式给出文件
发布于 2013-02-19 03:57:02
with open(<FILE>) as FileObj:
for lines in FileObj:
print lines # or do some other thing with the line...
将一次读取一行到内存,并在完成时关闭文件...
https://stackoverflow.com/questions/14944183
复制相似问题