python - 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 循环条件下尝试捕获。
解决方案
这行得通吗?(编辑为找到的解决方案 OP)
with open(input_file_path, "r", encoding="utf8", errors="surrogateescape") as input_file:
for line in input_file:
try:
yourcode
except:
continue
推荐阅读
- r - 识别向量的第一次出现,其中 15 个值中有 12 个为 1
- sql-server - 无法使用变量执行 SQL Server 存储过程(找不到存储过程)
- c++ - 为 QDoubleSpinBox 的多个实例创建一个公共插槽
- javascript - 使用 javascript 设置 PHP 表单数组变量
- python - Python for loop variable(K) in range(1,11) 如何在 HHkC 之类的词中使用并显示 HH1C、HH2C......HH10C?
- postgresql - 在 Postgres 中插入多个表时是否保留顺序
- multi-tenant - 将项目级用户分配给多个租户
- spring - 如何使用集群中的所有 pod 订阅亚马逊 SNS 主题?
- c# - 如何在托管的 MVC 应用程序中获取 Azure AD 对象 ID?
- java - 缓冲区链接和装饰原理 Java I/O