Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Output printed multiple times even after adding break

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To break out of both for loops try one of:

  • Split the for-loops into a separate function and return out of it
  • Use for-else construct to detect when inner loop used break and then break out of outer loop
  • raise an Exception in the inner loop and catch it outside the outer loop
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading