0

I have my code but it doesn't seem to work as expected. It needs to ask the user for input to search a file once found doesn't ask again but keeps asking. But I want it to ask the user again if the file hasn't been found. My code is as followed:

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")
phihag
  • 278,196
  • 72
  • 453
  • 469

3 Answers3

1

The problem is you're only breaking the inner loop (the for).

You can put this in a function and return instead of breaking, or raise and catch an exception, as suggested here: Breaking out of nested loops

Community
  • 1
  • 1
Vlad
  • 18,195
  • 4
  • 41
  • 71
1

break just aborts the inner for loop. You can simply use a helper variable:

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

Alternatively, make it a function and use 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()

You can also use the 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
phihag
  • 278,196
  • 72
  • 453
  • 469
0

The break is inside the for-loop so it only breaks you out of the for-loop not the while loop.

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")
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504