[英]print next line only if it begins with a specific word
我對python有點陌生,我想知道是否有人可以提供幫助。 基本上,我正在讀取文件的內容,當我找到單詞“ prb”時,我想使用next()函數檢查下一行,如果它以單詞“ rt”開頭,我想打印這兩行。 到目前為止,我編寫了這段代碼:
with open('/home/user/Desktop/3rdstep.txt', 'r') as f:
f.readline()
for line in f:
if "prb" in line:
try:
myword = next(f)
if "rt" in myword:
print(line.strip())
print(myword)
except:
print("pass")
這很好,但唯一的問題是由於我不知道的原因,它會隨機跳過“ rt”字樣。 有人可以幫忙還是有人做類似的事情?
謝謝
您可以使用if myword.startswith("rt"):
代替if "rt" in myword:
如果您的輸入有兩個以'prb'
開頭的連續行,然后是以'rt'
開頭的行,那么將跳過它們。 唯一的例外是它們是文件中的前三行。 這是因為for line in f:
中的行for line in f:
讀取以'prb'
開頭的第一行,而myword = next(f)
讀取第二行。 因此,在下面的迭代line
以'rt'
開頭。
無需閱讀下一行,您可以存儲上一行,然后檢查兩行是否匹配:
prev = ''
with open('/home/user/Desktop/3rdstep.txt') as f:
for line in f:
if prev.startswith('prb') and line.startswith('rt'):
print(prev.strip())
print(line)
prev = line
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.