文件访问前进

时间:2012-07-06 09:00:21

标签: python

我需要逐行读取文件,我需要查看“下一行”,所以首先我将文件读入列表然后循环浏览列表...不知怎的,这看起来很粗鲁,构建了列表可能变得昂贵。

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

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

3 个答案:

答案 0 :(得分:6)

您可能正在寻找类似于来自itertools的pairwise食谱。

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

答案 1 :(得分:1)

你可以这样做

last_line = None

for line in open(filename):                                                                  
    if last_line is not None:
        do_stuff(last_line, line) 
    last_line = line                                                        

答案 2 :(得分: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()