Python读取大文本文件(几GB)的最快方法
我有一个很大的文本文件(大约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
行一块一块地读取。
1 个回答
16
with open(<FILE>) as FileObj:
for lines in FileObj:
print lines # or do some other thing with the line...
会一次读取一行到内存中,完成后会关闭文件...