我有一個大文本文件(約7 GB)。我正在尋找是否存在閱讀大文本文件的最快方法。我一直在閱讀有關使用多種方法作為讀取chunk-by-chunk以加快進程的過程。
例如,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))
將返回n
文件的下一行列表f
。在循環中使用它將為您提供大量n
行的文件
解決方案
with open(<FILE>) as FileObj: for lines in FileObj: print lines # or do some other thing with the line...
將在此時讀取一行內存,並在完成后關閉文件...
本文首發於Python黑洞網,博客園同步更新