因此,在我撰寫的這部分代碼中,程式會在 else 陳述句中多次列印輸出。我試圖添加休息時間,但它仍然列印了 6 次。問題是什么?順便說一句,我是 python 新手 :) 這是代碼:
for Path in mapp:
if Path.is_file():
with Path.open("r") as file:
try:
for line in file.readlines():
if keyword in line:
keyword_files.append(str(Path))
Hittad = open("spara.txt", "a")
Hittad.write("S?kord hittad i:" str(Path) "\n")
Hittad.close()
print("S?kord hittad i:", "\n", str(Path))
else:
Intehittad = open("Intehittad.txt", "a")
Intehittad.writelines("Finns ej" "\n")
Intehittad.close()
print("Inte hittad")
except:
pass
uj5u.com熱心網友回復:
要跳出兩個 for 回圈,請嘗試以下方法之一:
- 將 for 回圈拆分為一個單獨的函式并從中分離
return出來 - 使用 for-else 構造來檢測何時使用內回圈
break然后break退出外回圈 Exception在內回圈中提出 an并在外回圈外捕獲它
uj5u.com熱心網友回復:
調查此類問題的最簡單方法是在您的 IDE 中使用除錯模式(我個人使用 PyCharm)。我認為在您的情況下,列印輸出是有效的,并且是嵌套 for 回圈的結果。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/388055.html
標籤:Python
上一篇:如果其他列相等,則對兩列求和
