itertools.islice https://docs.python.org/3/library/itertools.html#itertools.islice和两个参数iter
可以用来实现这一点,但这有点有趣:
from itertools import islice
n = 5 # Or whatever chunk size you want
with open(filename, 'rb') as f:
for n_lines in iter(lambda: tuple(islice(f, n)), ()):
process(n_lines)
这将保留islice
ing off n
一次行(使用tuple
实际上强制读入整个块)直到f
筋疲力尽,此时就会停止。最终块将小于n
行数(如果文件中的行数不是偶数倍)n
。如果您希望所有行都是单个字符串,请更改for
循环为:
# The b prefixes are ignored on 2.7, and necessary on 3.x since you opened
# the file in binary mode
for n_lines in iter(lambda: b''.join(islice(f, n)), b''):
另一种方法是使用izip_longest
为了这个目的,这就避免了lambda
功能:
from future_builtins import map # Only on Py2
from itertools import izip_longest # zip_longest on Py3
# gets tuples possibly padded with empty strings at end of file
for n_lines in izip_longest(*[f]*n, fillvalue=b''):
# Or to combine into a single string:
for n_lines in map(b''.join, izip_longest(*[f]*n, fillvalue=b'')):