这个问题已经在这里有一个答案:
- 如何读取大文件,一行行,在Python 10个回答
我有一个大的文本文件(〜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**
为了处理96900行每秒文字。 其他作者建议使用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
线