我需要通过一次最多读取N行来读取一个大文件,直到EOF。在Python中做这件事最有效的方法是什么?类似于:
with open(filename, 'r') as infile:
while not EOF:
lines = [get next N lines]
process(lines)
发布于 2011-04-29 21:55:11
一种解决方案是列表理解和切片运算符:
with open(filename, 'r') as infile:
lines = [line for line in infile][:N]
在此之后,lines
是行的元组。但是,这会将整个文件加载到内存中。如果你不想这样(即如果文件可能非常大),还有另一个解决方案,使用生成器表达式和来自itertools包的islice
:
from itertools import islice
with open(filename, 'r') as infile:
lines_gen = islice(infile, N)
lines_gen
是一个生成器对象,它提供文件的每一行,并可以在如下所示的循环中使用:
for line in lines_gen:
print line
这两种解决方案最多提供N行(如果文件没有那么多,也可以更少)。
发布于 2011-05-01 06:49:28
在Python中,文件对象是行上的迭代器。要一次迭代文件N行,可以在文档的Itertools Recipes部分使用grouper()
函数。(另请参阅What is the most “pythonic” way to iterate over a list in chunks?):
try:
from itertools import izip_longest
except ImportError: # Python 3
from itertools import zip_longest as izip_longest
def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return izip_longest(*args, fillvalue=fillvalue)
示例
with open(filename) as f:
for lines in grouper(f, N, ''):
assert len(lines) == N
# process N lines here
发布于 2011-04-29 21:51:07
这段代码可以处理文件中任何数量的行和任何N
。如果你在文件和N = 200
中有1100 lines
,你将得到5次处理200行的块,一次处理100行。
with open(filename, 'r') as infile:
lines = []
for line in infile:
lines.append(line)
if len(lines) >= N:
process(lines)
lines = []
if len(lines) > 0:
process(lines)
https://stackoverflow.com/questions/5832856
复制相似问题