我有一个非常大的文件4GB,当我尝试阅读它时,我的电脑挂起.所以我想逐一阅读它并在处理完每件之后将处理过的零件存储到另一个文件中并阅读下一篇文章.
yield
这些作品有什么方法吗?
我很想拥有一种懒惰的方法.
我有一个大文本文件(约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**
Run Code Online (Sandbox Code Playgroud)
为了每秒处理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
Run Code Online (Sandbox Code Playgroud)
list(islice(f, n))
将返回n
文件的下一行列表f
.在循环中使用它将为您提供大量n
行的文件