【问题标题】:Is there any way to fix Unicodedecodeerror: 'utf-8' - python有什么方法可以修复 Unicodedecodeerror: \'utf-8\' - python
【发布时间】:2022-10-18 01:07:48
【问题描述】:

我的电子邮件验证器工具出现问题,它不会突然解码。

我有这个错误:

  File "C:\Users\vk662\OneDrive - ST\Skrivebord\test\email_check.py", line 70, in <module>
for row in csv_reader:


File "C:\Program Files\Python310\lib\codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 4: invalid continuation byte

这是代码:在第 70 行;

 email_list = []
with open('email_in/test.csv', 'r', encoding='utf-8') as read_obj:
    csv_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_reader:
        if (row):
            result = email_check(row[0],email_list)
            if result["Email ok"]:
                email_list.append(row[0])
            if result["Email ok"]:
                email_ok.append(row[0])
            else:
                str = "~~"
                for x, y in result.items():
                    if y:
                        str += x + "~~"
                    if x == "Duplicate email" and y:
                        if row[0] in email_ok:
                            email_ok.remove(row[0])
                email_error.append(row[0] + str)

查看下图:https://imgur.com/DE3sdQN

【问题讨论】:

  • CSV 文件似乎有另一种编码为“utf-8”。
  • @MichaelButscher我该如何解决?
  • 找出使用了哪种编码。如果大部分文件以 Ascii 编码,您可以将参数 errors='replace' 添加到 open 调用中。这将用问号替换无法识别的字节。

标签: python unicode utf-8 decode


【解决方案1】:

正如 Michael Butscher 所说,我还建议您使用不同的编码。尝试使用西方国家的主要编码“latin-1”或“cp1252”。

另一种解决方案是使用 utf-8 编码保存您的 .csv 文件。然后打开 csv 部分可能会起作用。 为此,谷歌“如何将 excel csv 文件保存为 utf-8”。 (我的 excel 显示非英文,所以我不能准确地告诉你每一步。英文指南会帮助你。)

如果您使用 MS excel 制作了 .csv 文件,那么这可能是原因。 excel 通常使用非 utf-8 编码保存文件。

这一段是你得到错误的原因。 只有 0x80 和 0xBF 之间的十六进制值可以用作多字节 utf-8 表示中的非首字节。 0xe5 超出范围。这就是计算机返回“无效的继续字节”的原因

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 2018-05-05
    相关资源
    最近更新 更多