逐行读取文件时读取上下行
我想用Python逐行读取一个文件,如果某一行符合某些条件,我想返回它的前一行和下一行。有什么最好的(最符合Python风格的)方法来实现这个呢?我想做的事情大概是这样的:
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 个回答
2
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
我觉得这是一个稍微好一点的设计模式……其实还有其他更符合Python风格的方法可以做到这一点,这要看具体是要实现什么功能……