6

我需要逐行读取文件,并且需要查看“下一行”,因此首先我将文件读入列表,然后循环浏览列表...不知何故,这似乎很粗鲁,构建列表可能是变得昂贵。

for line in open(filename, 'r'):
    lines.append(line[:-1])

for cn in range(0, len(lines)):
    line = lines[cn]
    nextline = lines[cn+1] # actual code checks for this eof overflow

必须有更好的方法来迭代线路,但我不知道如何向前看

4

3 回答 3

6

您可能正在寻找类似 itertools 的pairwise recipe 的东西。

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

with open(filename) as f: # Remember to use a with block so the file is safely closed after
    for line, next_line in pairwise(f):
        # do stuff
于 2012-07-06T09:07:05.610 回答
1

你可以这样做

last_line = None

for line in open(filename):                                                                  
    if last_line is not None:
        do_stuff(last_line, line) 
    last_line = line                                                        
于 2012-07-06T09:05:40.230 回答
0

您可以创建一个iterator并这样做:

f = open(filename, 'r')
g = open(filename, 'r')

y = iter(g.readlines())
y.__next__()

for line in f:
    print(line)
    try:
        print(y.__next__())
    except StopIteration:
        f.close()
        g.close()
于 2012-07-06T09:39:59.653 回答