break
只是中止内部 for 循环。您可以简单地使用辅助变量:
import os, sys
while True:
lookfor=input("\nPlease enter file name and extension for search? \n")
found = False
for root, dirs, files in os.walk("C:\\"):
print("Searching", root)
if lookfor in files:
print("Found %s" % os.path.join(root, lookfor))
found = True
break
if found:
break
print ("File not found, please try again")
或者,将其设为函数并使用return
:
def search():
while True:
lookfor=input("\nPlease enter file name and extension for search? \n")
for root, dirs, files in os.walk("C:\\"):
print("Searching", root)
if lookfor in files:
print("Found %s" % os.path.join(root, lookfor))
return
print ("File not found, please try again")
search()
您还可以使用for..else
构造:
while True:
lookfor=input("\nPlease enter file name and extension for search? \n")
for root, dirs, files in os.walk("C:\\"):
print("Searching", root)
if lookfor in files:
print("Found %s" % os.path.join(root, lookfor))
break
else:
print ("File not found, please try again")
continue
break