Reputation: 29
I'm trying to make a script where someone can type a username and the script will check if the directory exists, returning true or false as it goes through the list. Currently, the output is always "Not found"/false even though there should definitely be at least one true returned.
def scan():
username = input("Type in the username here: ")
i = 0
searchFor = folderList[i] + username
listLength = len(folderList)
while i < listLength:
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
For reference, this code below which doesn't use a loop works fine, as if I type in the username and the correct index for the element of the directory that exists, it returns true, otherwise if I choose another index it's false as it should, so it's not an issue with the elements or folder permissions.
def test():
username = input("Type in the username here: ")
i = int(input("Type list index number here: "))
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print("Folder found: " + searchFor)
else:
print("Not found!")
Would appreciate any help!
Upvotes: 0
Views: 224
Reputation: 99
def scan():
username = input("Type in the username here: ")
i = 0
listLength = len(folderList)
while i < listLength:
searchFor = folderList[i] + username
if os.path.isdir(searchFor) == True:
print ("Folder found!")
i += 1
elif os.path.isdir(searchFor) == False:
print ("Not found")
i += 1
Upvotes: 1
Reputation: 45750
I'm writing an answer because the existing answers fail to address the problem, and I think they confuse things more than anything.
You currently have searchFor
outside of the loop. As a result, it will be given a value once before the loop is entered, then its value is never changed. If you want its value to change, you must manually reassign it:
while i < listLength:
searchFor = folderList[i] + username
Although, really, a for
loop should be used here instead (but not as @Sai suggests):
for folder in folderList:
searchFor = folder + username
You never use i
for anything other than indexing folderList
, so you should just iterate the folderList
directly instead. Iterating a range
is generally regarded as a code smell if you're just using the number to index a list.
Upvotes: 2
Reputation: 285
This code will help you
def scan():
username = input("Type in the username here: ")
is_exists = False
for i in range(0,len(folderList)):
searchFor = folderList[i] + username
if os.path.isdir(searchFor):
is_exists = True
break
if is_exists:
print("Search is found")
else:
print("Not Found")
Upvotes: 1