如何告诉用户发生线路错误的位置?

时间:2017-03-28 04:10:41

标签: python python-3.x

我试图合并枚举,这样我就可以给程序的用户提供行错误和该行的输入。

这是我的代码:

elif response == 'data2':
    print('Processing file:', response + '.txt')
    try:
        infile = open('data2.txt', 'r')
        for line in infile:
            amount = float(line)
            total += amount
        infile.close()
        print(format(total, ',.2f'))

    except IOError:
        print("IO Error occurred trying to read the file.")
    except ValueError:
        print("Non-numeric data found in file:", response + '.txt')
    except:
        print("An error occurred.")

如您所见,我希望ValueError输出以下内容:

  

在文件中找到非数字数据:data2.txt在第3行:输入:3   百

然而,我仍然坚持如何实现这一目标。

2 个答案:

答案 0 :(得分:2)

您可以使用enumerate内置功能获取行号:

elif response == 'data2':
    print('Processing file:', response + '.txt')
    try:
        # Python allows you to iterate over a file object directly.
        for line_no, line in enumerate(open('data2.txt', 'r')):
            amount = float(line)
            total += amount
        print(format(total, ',.2f'))
    except IOError:
        print("IO Error occurred trying to read the file.")
    except ValueError:
        # I took the liberaty of formatting your output in a way
        # that's a bit more readble than one long line of text.
        print("Non-numeric data found in file: {}.txt at line: {}"
              "with input: {}".format(response, line_no + 1, line))
    except:
        print("An error occurred.")

答案 1 :(得分:0)

您需要跟踪文件中的哪一行,并在阅读时捕获异常。

for line_number, line in enumerate(infile, 1):
    try:
        amount = float(line)
    except ValueError:
        print(
            "Non-numeric data found in file",
            response + ".txt on line",
            line_number,
            "with input",
            line
        )
        exit(1)  # or whatever is appropriate for this script.