逐批读取文件中的多行

Read multiple lines from a file batch by batch

我想知道有没有一种方法可以逐批读取文件中的多行。例如:

with open(filename, 'rb') as f:
    for n_lines in f:
        process(n_lines)

在这个函数中,我想做的是:对于每次迭代,将从文件中逐批读取接下来的 n 行。

因为单个文件太大。我想做的是一段一段地看。

您实际上可以遍历文件中的行(请参阅 file.next 文档 - 这也适用于 Python 3),例如

with open(filename) as f:
    for line in f:
        something(line)

所以你的代码可以重写为

n=5 # your batch size
with open(filename) as f:
    batch=[]
    for line in f:
        batch.append(line)
        if len(batch)==n:
            process(batch)
            batch=[]
process(batch) # this batch might be smaller or even empty

但通常逐行处理更方便(第一个示例)

如果您不关心每个批次究竟读取了多少行,而只是关心它不是太多内存,那么使用 file.readlinessizehint like

size_hint=2<<24 # 16MB
with open(filename) as f:
    while f: # not sure if this check works
        process(f.readlines(size_hint))

itertools.islice 和两个 arg 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 一次关闭 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'')):