逐行读取文件时读取下一行和上一行

时间:2014-04-02 23:01:04

标签: python for-loop io

使用Python,我想逐行读取一些文件,如果一行符合某些条件,我想返回上一行和下一行。什么是最好的(最pythonic)方式呢?我想做这样的事情:

with open(filename, 'r') as f:
    for line in f:
        if line.find("some string") != -1:
            print get_previous_line
            print get_next_line

修改

事实证明我需要阅读上一行,并且没有previous功能。问题标题和脚本相应地修改了......

1 个答案:

答案 0 :(得分:1)

active = False
previous = None
with open(filename, 'r') as f:
    for line in f:
        prev = previous #this is the previous line now
        previous = line 
        if active: #active contains previous line ...
           do_something_with_line_after_some_string(prev,line) #terrible function name but you get the idea
        elif line.find("some string") != -1:
           active = line
           continue
        active = False

是一个稍好的设计模式imho ...真的还有其他更多的pythonic方法来做到这一点,这取决于它实际上在做什么......