0

我有我的代码,但它似乎没有按预期工作。它需要询问用户输入以搜索文件,一旦找到就不会再次询问,而是继续询问。但我希望它再次询问用户是否找不到文件。我的代码如下:

import os, sys
from stat import *
from os.path import join

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" % join(root, lookfor))
            break
        else:
            print ("File not found, please try again")
4

3 回答 3

1

问题是你只是打破了内循环(the for)。

您可以将它放在一个函数中并返回而不是中断,或者引发并捕获异常,如下所示:Breaking out of nested loops

于 2013-04-30T21:48:46.710 回答
1

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
于 2013-04-30T21:49:50.393 回答
0

break在 for 循环内,所以它只会让你脱离 for 循环而不是while循环。

import os, sys
from stat import *
from os.path import join

condition=True 

while condition:
    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" % join(root, lookfor))
            condition = False      #set condition to False and then break
            break
        else:
            print ("File not found, please try again")
于 2013-04-30T21:48:45.647 回答