python - python 中循环条件出错时如何继续?

标签 python loops error-handling

我有循环文件的 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/

相关文章:

python - pretty-print 并替换 numpy 数组

c++ - 程序崩溃而没有错误消息

php - 这是try-catch-finally的可接受用法吗?

java - 基础设施或预检查错误 : No class with name found

python - Sympy 旋转方向矩阵

python - PyQt中如何调用多个Dialog?

r - 将 pnorm 应用于数据框的列

windows - 批处理字符串操作中的进度条

Angular Material SnackBar 和自定义 ErrorHandler 来通知错误

python - 我怎样才能用这样的高斯函数做更好的曲线拟合?