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?
CodePudding user response:
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")
CodePudding user response:
How can I fix this?
Use an exact equality predicate? in
is a containment operation, it checks that myIDList
contains myID
.
And since myIDList
is a string, that's a substring check.
Also... why are you manually iterating on whatever pathlist
is supposed to be? The entire thing seems rather wrong-headed. If you have a structure of the form $DIRECTORY/$USER_ID.ext
, you can just compose a path using that (using pathlib
, or os.path.join
), then check that that exists / operate on this. The iteration seems entirely unnecessary.