简体   繁体   English

如果文件不存在则重新运行代码不起作用

[英]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如果我尝试将 while 循环带到外面,那么它会在文件不存在的情况下工作,但如果文件存在,代码只是在循环后停止而不是接下来运行 function,这是代码

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.在主 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显然,如果禁用调试,断言将不起作用,但你明白了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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