So in this part of the code im writing, the program keeps printing the output multiple times in the else statment. I tried to add the break but it´s still printing 6 times. What is the problem? Im new to python btw 🙂
Here is the code:
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
>Solution :
To break out of both for loops try one of:
- Split the for-loops into a separate function and
returnout of it - Use for-else construct to detect when inner loop used
breakand thenbreakout of outer loop - raise an
Exceptionin the inner loop and catch it outside the outer loop