Python程序在不能使用时保持循环

时间:2013-04-30 21:46:18

标签: python

我有我的代码,但它似乎没有按预期工作。它需要询问用户输入以便在找到后不再询问但仍在询问的情况下搜索文件。但我希望它再次询问用户是否找不到该文件。我的代码如下:

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")

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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 construct

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

答案 2 :(得分: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")