在处理文件时找出异常的位置
Finding out the position of an exception while processing a file
我正在处理 Python 中的一些半结构化文档,我有一些代码可以将文件读入元组并循环遍历每一行并执行一个函数。有没有办法找到已处理文件中遇到错误的确切行?
c = tuple(open("file", 'r'))
for element in c:
if (condition is met):
do something
else:
do something else
结果应该是:
Error: in line # of "file"
enumerate
应该有帮助:
for line, element in enumerate(c):
try:
if (condition is met):
do something
else:
do something else
except Exception as e:
print('got error {!r} on line {}'.format(e, line))
以上会给出如下错误:
got error OSError('oops!',) on line 4
虽然作为一种好的做法,您通常会将 Exception
替换为您希望捕获的任何错误。
一般来说,在读取文件时使用 with
关键字是一种很好的做法,尤其是当您预计会发生异常时。您也可以enumerate
来计算行数:
with open(filename) as f:
for line_num, line in enumerate(f):
try:
if (condition is met):
do something
else:
do something else
except Exception:
print('Error: in line {:d} of file'.format(line_num))
如果您知道您期望的特定异常,最好不要使用 Exception
,因为它会捕获所有异常,即使是您不期望的异常。
我正在处理 Python 中的一些半结构化文档,我有一些代码可以将文件读入元组并循环遍历每一行并执行一个函数。有没有办法找到已处理文件中遇到错误的确切行?
c = tuple(open("file", 'r'))
for element in c:
if (condition is met):
do something
else:
do something else
结果应该是:
Error: in line # of "file"
enumerate
应该有帮助:
for line, element in enumerate(c):
try:
if (condition is met):
do something
else:
do something else
except Exception as e:
print('got error {!r} on line {}'.format(e, line))
以上会给出如下错误:
got error OSError('oops!',) on line 4
虽然作为一种好的做法,您通常会将 Exception
替换为您希望捕获的任何错误。
一般来说,在读取文件时使用 with
关键字是一种很好的做法,尤其是当您预计会发生异常时。您也可以enumerate
来计算行数:
with open(filename) as f:
for line_num, line in enumerate(f):
try:
if (condition is met):
do something
else:
do something else
except Exception:
print('Error: in line {:d} of file'.format(line_num))
如果您知道您期望的特定异常,最好不要使用 Exception
,因为它会捕获所有异常,即使是您不期望的异常。