python 2.7: 只读文件到已知行

python 2.7: reading a file only up to a known line

如果我想从给定的行开始阅读,我可以这样做:

with open(myfile) as f:
  for x in range(from_here):
    next(f)

  for line in f:
    do stuff

如何做相反的事情:只读取给定的行?

我在考虑 for 循环:还有其他方法吗?

with open(myfile) as f:
    for x in range(until_here):
        line = next(f)
        # do stuff with line
    # do stuff with the rest of f

import itertools as it
with open(myfile) as f:
    for line in it.islice(f, until_here):
        # do stuff
    # do stuff with the rest of f

显而易见的答案是使用一个只计算的循环:

with open(myfile) as f:
    for i in xrange(number_of_wanted_lines):
        line = next(f)
        # do stuff with line

关于你问题的第二部分,你也可以将整个文件读入一个行列表,然后使用切片:

with open(myfile) as f:
    lines = f.readlines()[start_line_number:end_line_number+1]
    for line in lines:
        # do stuff with line

如果你不想将整个文件加载到内存中,你也可以使用islice(来自itertools)而不是列表切片:

import itertools

with open(myfile) as f:
    for line in itertools.islice(f, start_line_number, end_line_number + 1):
        # do stuff with line