我有循环文件的 python 代码。当我读取文件时,出现 UTF-8 错误(无效的连续字节)
。我只是希望我的程序忽略它。
我尝试在内部代码周围使用 try except ,但这不起作用,因为错误是在 for 循环的条件下发生的。我还尝试过在循环周围使用 try except ,但是当它捕获错误时,它不会再次启动循环。
with open(input_file_path, "r") as input_file:
for line in input_file:
# code irrelevant to question
发生的情况是在for line in input_file
上出现此错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position 5: invalid continuation byte`
我希望它跳过该行并移至下一行。本质上,是对我的 for 循环条件的 try catch。
最佳答案
这个有用吗? (编辑到找到的解决方案OP)
with open(input_file_path, "r", encoding="utf8", errors="surrogateescape") as input_file:
for line in input_file:
try:
yourcode
except:
continue
关于python - python 中循环条件出错时如何继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249832/