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

Break from for loop and match exact file name in Python

Here is my code:

import os

folderPath= "my images folder path"
pathList = os.listdir(folderPath)
myID = input("Enter Your ID: ")
for path in pathList:
    myIDList = os.path.splitext(path)[0]
    if myID in myIDList:
        print(myIDList)
    else:
        print("Incorrect")

The output is printing in the loop but I need exact match of the filename. If I enter half of the filename, it shows that the file exists. How can I fix this?

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

>Solution :

you have to use a flag variable. and also, in operation checks for substrings, which is the reason it shows file exists for partial inputs. use == for exact match.

although it seems there are many other issues with this (including iterating over the pathlist), this might help you get started and understand where you made the mistakes

import os

pathList = "my images folder path"
myID = input("Enter Your ID: ")
flag = False
for path in pathList:
    myIDList = os.path.splitext(path)[0]
    
    #using strict check instead of 'in'
    if myID == myIDList:   
        #using flag over breaking the loop when result is achieved
        flag = True
        break 
if flag:
    print("correct")
else:
    print("Incorrect")
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