0

I want the user to enter a path to a directory as input. The program should check if this path really exists. If the path exists it should execute the rest of the code.

If the path does not exist it should print that it is a non existing path and I want it to request the user again to input a path, until the user enters a path that exists.

I have tried it with a while loop, with try and except and with if and else statements but I can't get it error free.

This is my current code:

i = 0

while i<1:

    input = input("Please enter path to directory: ")
    if os.path.exists(input) == False:
        print("This path does not exist")


    elif os.path.exists(input) == True:
        os.chdir(input)
        execute_code(input)
        i +=1

If the user enters an existing path everything works fine, but if the path does not exist it prints that the path does not exist but it will show an error and will not request again for input.

What do I need to change so the program will ask the user again for input?

  • 2
    Use a different variable name than `input`, it shadows the `input` function that you would like to use. – mkrieger1 May 01 '19 at 12:29
  • As @mkrieger1 said, don't use `input` as a variable name, code written as is working once you change that. – icwebndev May 01 '19 at 12:31
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – glibdud May 01 '19 at 12:33
  • I'd recommend using os.path.isdir() rather than os.path.exists(), because the latter will return true even if the path is a file, but when you do os.chdir(input) it will throw NotADirectoryError. – Astroynamicist May 01 '19 at 13:00

2 Answers2

3

Few pointers to take care of:

  1. Never use a reserved keyword as a variable name
  2. Don't need an elif condition here coz there can only be two return values from os.path.exists(input_path) either True or False

Below is the updated code

while True:
    input_path = input("Please enter path to directory: ")
    if not os.path.exists(input_path):
        print("This path does not exist")
    else:
        os.chdir(input_path)
        execute_code(input_path)
        break

Hope this helps!

Kaushal Pahwani
  • 464
  • 3
  • 11
1

you can use continue to start loop over and break to exit loop:

while True:

    user_input = input("Please enter path to directory: ")
    if os.path.exists(user_input) == False:
        print("This path does not exist")
        continue  # it will start from loop begining

    os.chdir(user_input)
    execute_code(user_input)
    break  # exit loop
icwebndev
  • 413
  • 3
  • 10
Mahmoud Elshahat
  • 1,873
  • 10
  • 24