[英]Continue for loop after caught Exception
I am reading a large (2Gb) file via csv.DictReader
(for what it matters).我正在通过csv.DictReader
读取一个大(2Gb)文件(重要的是)。 Somewhere deep in the file there is an issue with the coding and I get a UnicodeDecodeError
.文件深处的某个地方存在编码问题,我收到了UnicodeDecodeError
。 Looking at the error message I see that the error is raised in the implicit __next__
in my for
loop.查看错误消息,我看到错误是在我的for
循环中的隐式__next__
中引发的。
Code stub would look at follows:代码存根将查看以下内容:
import csv
with open("myfile.csv", newline="") as f:
c = csv.DictReader(f)
for line in c: # here the error is happening
pass
I want to use a try-except
pattern to catch any reading error, logging a meaningful message and continue reading through the file.我想使用try-except
模式来捕获任何读取错误,记录一条有意义的消息并继续读取文件。
How could I achieve that?我怎么能做到这一点? I cannot use continue
outside the loop (ie in the except
block) so I guess I would need to rewrite the for
loop in order not to use the implicit form but an explicit one, but as I am fairly new to python, I do not know how to do that in the most pythonic way.我不能在循环外使用continue
(即在except
块中),所以我想我需要重写for
循环,以便不使用隐式形式而是显式形式,但由于我对 python 相当陌生,我不知道如何以最 Pythonic 的方式做到这一点。
To simulate the error look at the following toy example:要模拟错误,请查看以下玩具示例:
class MyIterator:
def __init__(self, mclass):
self._mclass = mclass
self._index = 0
def __next__(self):
if self._index == 3:
# simulate an error in a file read
self._index += 1
raise Exception("simulated error"
elif self._index < 5:
self._index += 1
return self._index - 1
# End of Iteration
raise StopIteration
class MyClass:
def __iter__(self):
return MyIterator(self)
obj = MyClass()
try:
for result in obj:
print(result)
except Exception as e:
print("Exception covered")
## does not work for obvious reasons:
# continue
只是为了记录,而不是试图在next
上捕获错误,您可以将errors
参数传递给open
,这决定了如何处理编解码器错误。
Wrap your object in an iter and call next on it in a while loop将您的对象包装在一个 iter 中并在 while 循环中调用 next
done = False
obj = iter(MyClass())
while not done:
try:
data = next(obj)
except StopIteration:
done = True
except Exception:
print("process error here and continue")
What python version are u using?你用的是什么python版本? Also why not using yield ( see enter link description here )另外为什么不使用 yield (请参阅此处输入链接描述)
You can return instead of raise.您可以返回而不是加注。 If you know if type(variable) is Exception you cand process information.如果您知道 type(variable) 是否为 Exception 您可以处理信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.