Search code examples
pythonerror-handlingtry-catch

Rerun code if file doesn't exist is not working


I have this code to read a file

def collect_exp_data(file_name):
    data = dict()
    while True:
        try:
           with open(file_name, 'r') as h:
                break
                for line in h:
                batch, x, y, value = line.split(',')                            
                try: 
                    if not batch in data:
                        data[batch] = []
                    data[batch] += [(float(x), float(y), float(value))]
                except ValueError: 
                    print("\nCheck that all your values are integers!")   
        except FileNotFoundError:
            print("\nThis file doesn't exist, Try again!")
    return data

I'm trying to add some error handling, i want to re ask the user to enter file in case the file doesn't exist, but the code is just returning an endless loop! what did I do wrong and how can I fix it?

Edit:

If i try and take the while loop outside, then it works in case file doesn't exists, but if file exists, the code is just stopping after the loop and not running next function, here is the code

def collect_exp_data(file_name):
    data = dict()
    with open(file_name, 'r') as h:
        for line in h:
            batch, x, y, value = line.split(',')                           
        try: 
            if not batch in data:
                data[batch] = []
            data[batch] += [(float(x), float(y), float(value))]
        except ValueError: 
            print("\nCheck that all your values are integers!")   
    return data

while True:
    file_name = input("Choose a file: ")
    try:
        data = collect_exp_data(file_name)
        break
    except FileNotFoundError:
        print('This file does not exist, try again!')

Solution

  • Make a condition to break the loop

    finished = False
    while not finished:
        file_name = input("Choose a file: ")
        try:
            data = collect_exp_data(file_name)
            # we executed the previous line succesfully,
            # so we set finished to true to break the loop
            finished = True
        except FileNotFoundError:
            print('This file does not exist, try again!')
            # an exception has occurred, finished will remain false
            # and the loop will iterate again