首页 > 解决方案 > python - 如何在python中的循环条件错误中继续?

问题描述

我有循环文件的python代码。(invalid continuation byte)读取文件时出现 UTF-8 错误。我只是希望我的程序忽略这一点。

我试过使用 try 除了围绕里面的代码,但这不起作用,因为错误是在 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 循环条件下尝试捕获。

标签: pythonloopserror-handling

解决方案


这行得通吗?(编辑为找到的解决方案 OP)

with open(input_file_path, "r", encoding="utf8", errors="surrogateescape") as input_file:
    for line in input_file:
        try:
            yourcode
        except:
            continue

推荐阅读