0

I want the program to tell the user that the file he has wrote is not available (in case he wrote the name of a file that does not exist) and then to give him the oppourtinity to input a valid file name till he writes a valid file name.

def openfile(which_file): 

    with open(which_file, "r") as file: 
        file_rows=file.readlines()
        passengers=[]
        for lines in file_rows:
            if lines !="\n":
                objekt=carclass.data_manager(lines.split()[0], lines.split()[1], lines.split()[2], lines.split()[9], lines.split()[13])
                passengers.append(objekt)
        return passengers
    

def mainmenu(): 


    which_file = input("Which file do you want to read?: ")
    passengers = openfile(which_file)

Future
  • 57
  • 6
  • Please update the indentation of your code. Python is very sensitive to indentation, as are python programmers. – quamrana Jan 11 '21 at 16:33

1 Answers1

2
valid_file = False
while not valid_file:
    dest_file = input("Enter file's path: ")
    try:
        retval = openfile(dest_file)
    except FileNotFoundError:
        print("Invalid file path given")
    else:
        valid_file = True
Or Y
  • 2,088
  • 3
  • 16
  • Where should I write that? I mean should I write in a new function or is main menu function okay to write this in? – Future Jan 11 '21 at 16:49
  • @Future that's more on your side to decide, I believe that it would be acceptable both in the main function or in a separate name with an appropriate name, as long as you keep your function in a legitimate length. – Or Y Jan 11 '21 at 16:54