[英]Read next and previous lines while reading file line-by-line
使用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
功能。 問題標題和腳本已相應修改...
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
是一個稍微好一點的設計模式,恕我直言...實際上,還有其他更多的pythonic方法可以執行此操作,具體取決於這實際上在做什么...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.