我正在尝试制作一个脚本,其中有人可以键入用户名,脚本将检查目录是否存在,在列表中返回true或false。目前,输出总是"未找到"/false,尽管肯定至少应该返回一个true。
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
作为参考,下面的这段不使用循环的代码运行得很好,就好像我为存在的目录的元素键入用户名和正确的索引一样,它会返回true,否则,如果我选择另一个索引,它应该是false,所以元素或文件夹权限没有问题。
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!")
非常感谢您的帮助!
我之所以要写一个答案,是因为现有的答案无法解决问题,我认为它们更容易混淆问题。
您当前在循环的外部有searchFor
。因此,在进入循环之前,它将被赋予一个值一次,然后它的值永远不会改变。如果你想改变它的值,你必须手动重新分配它:
while i < listLength:
searchFor = folderList[i] + username
尽管,实际上,这里应该使用for
循环(但不是像@Sai建议的那样(:
for folder in folderList:
searchFor = folder + username
除了索引folderList
之外,您永远不会将i
用于其他任何事情,因此您应该直接迭代folderList
。如果您只是使用数字来索引列表,那么对range
进行迭代通常被视为一种代码气味。
此代码将帮助您
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")
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