简体   繁体   中英

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!')

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

Do all your exception handling in the main function.

def collect_exp_data(filename):
    data = dict()
    with open(filename) as infile:
        for line in map(str.strip, infile):
            batch, *v = line.split(',')
            assert batch and len(v) == 3
            data.setdefault(batch, []).extend(map(float, v))
    return data

while True:
    filename = input('Choose file: ')
    try:
        print(collect_exp_data(filename))
        break
    except FileNotFoundError:
        print('File not found')
    except (ValueError, AssertionError):
        print('Unhandled file content')

Obviously the assertion won't work if debug is disabled but you get the point

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM