【问题标题】:Python 2.7: how to read only a few lines at a time from a file?Python 2.7:如何一次从文件中读取几行?
【发布时间】:2011-07-13 01:25:55
【问题描述】:

例如,我在一个文件中有 2,000 行,我想一次读取 500 行,并在读取另外 500 行之前对这 500 行做一些事情。我想知道是否有人会编写一些快速代码供我学习。谢谢!

【问题讨论】:

  • 向我们展示您现在拥有的代码,我们将从那里开始。

标签: python file


【解决方案1】:

您可以使用生成器将这些行组合在一起,并以一种便于在简单 for 循环中使用的方式生成它们。这可能会让你开始:

def chunks_of(iterable, chunk_size=500):
    out = []
    for item in iterable:
        out.append(item)
        if len(out) >= chunk_size:
            yield out
            out = []
    if out:
        yield out

然后你可以这样使用:

for chunk_of_lines in chunks_of(file('/path/to/file'), chunk_size=500):
    # chunk_of_lines is 500 or fewer lines from the file

(为什么是“500 或更少”?因为如果文件中的行数不是 500 的偶数倍,最后一个块可能不是 500 行。)

编辑:始终先检查文档。这是来自the itertools docs的食谱

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

这会在可迭代对象(在本例中为文件对象)上创建 n 个迭代器列表——因为它们都是同一个底层对象上的迭代器,当一个迭代器前进时,其余迭代器将全部也提前 - 然后压缩他们的结果。 izip_longestizip 一样工作,但用 fillvalue 填充其结果,而不是像我的 chunks_of 函数那样简单地省略它们。

【讨论】:

  • 我认为对于绝对初学者来说,生成器解决方案太复杂了。如果他们不能编写一个简单的循环,他们就不会理解生成器和 yield 语句。
  • @eryksun d'oh!谢谢,好点子——现在这对我来说更有意义了。
【解决方案2】:

您也可以使用itertools.islice 一次读取 500 行:

lines = itertools.islice(file_obj, 500)

【讨论】:

    【解决方案3】:

    请纠正我,但我认为这个非常基本的示例也可以:

    linesToProceed = 500
    with open(filename, 'r') as f:
        lines = []
        for i,line in enumerate(f):
            if (i + 1) % linesToProceed:
                # do something with lines in lines
                lines = []
            else:
                lines.append(line)
    

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 2012-07-09
      • 2016-05-09
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      相关资源
      最近更新 更多