Python最快的方式來讀取大文本文件(幾GB)


我有一個大文本文件(約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黑洞網,博客園同步更新


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM