【问题标题】:UnicodeEncodeError when reading a file读取文件时出现 UnicodeEncodeError
【发布时间】:2016-10-04 16:10:36
【问题描述】:

我正在尝试从 rockyou 单词列表中读取并将所有 >= 8 个字符的单词写入一个新文件。

这里是代码 -

def main():
    with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w') as out_file:
        for line in in_file:
            if len(line.rstrip()) < 8:
                continue
            print(line, file = out_file, end = '')
        print("done")

if __name__ == '__main__':
    main()

有些词不是 utf-8。

Traceback (most recent call last): File "wpa_rock.py", line 10, in <module> main() File "wpa_rock.py", line 6, in main print(line, file = out_file, end = '') File "C:\Python\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u0e45' in position 0: character maps to <undefined>

更新

def main():
with open("rockyou.txt", encoding="utf8") as in_file, open('rockout.txt', 'w', encoding="utf8") as out_file:
    for line in in_file:
        if len(line.rstrip()) < 8:
            continue
        out_file.write(line)
    print("done")

if __name__ == '__main__':
    main()```

Traceback (most recent call last): File "wpa_rock.py", line 10, in <module> main() File "wpa_rock.py", line 3, in main for line in in_file: File "C:\Python\lib\codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf1 in position 933: invali d continuation byte

【问题讨论】:

  • 这是一个错字。它应该是 utf-8 而不是 utf8
  • 不知道是不是。使用任何一个都会导致相同的错误。
  • 您在该位置必须有一个无效字符。您应该显示您正在尝试读取的文件。
  • @Arpan:不,不是。 'utf8''utf-8' 都可以,一个是另一个的别名。
  • @MarkEvans 您是否尝试在打开输出文件时添加encoding="utf8"。我现在没有windows机器,所以不能查。

标签: python python-3.x unicode character-encoding


【解决方案1】:

您的UnicodeEncodeError: 'charmap' 错误发生在写入out_fileprint())期间。

默认情况下,open() 使用 locale.getpreferredencoding(),这是 Windows 上的 ANSI 代码页(例如 cp1252),它不能代表所有 Unicode 字符,尤其是 '\u0e45' 字符。 cp1252 是一种单字节编码,最多可以表示 256 不同的字符,但有一百万个 (1114111) Unicode 字符。它不能代表所有这些。

通过encoding,它可以代表所有需要的数据,例如,encoding='utf-8' 必须工作(如@robyschek suggested)——如果您的代码读取utf-8 数据没有任何错误,那么代码应该能够使用写入数据utf-8 也是。


在读取in_file (for line in in_file) 时出现UnicodeDecodeError: 'utf-8' 错误。并非所有字节序列都是有效的 utf-8,例如,os.urandom(100).decode('utf-8') 可能会失败。具体操作取决于应用程序。

如果您希望文件被编码为 utf-8;你可以通过 errors="ignore" open() 参数,忽略偶尔的无效字节序列。或者你可以使用some other error handlers depending on your application

如果文件中使用的实际字符编码不同,那么您应该传递实际字符编码。 bytes 本身没有任何编码——元数据应该来自另一个来源(尽管 some encodings are more likely than others: chardet can guess)例如,如果文件内容是 http 正文,那么请参阅 A good way to get the charset/encoding of an HTTP response in Python

有时,损坏的软件可以生成大部分 utf-8 字节序列,其中一些字节采用不同的编码。 bs4.BeautifulSoup can handle some special cases。您也可以try ftfy utility/library 看看它是否对您有帮助,例如ftfy may fix some utf-8 variations

【讨论】:

  • 更新了问题。
【解决方案2】:

嘿,我遇到了类似的问题,在rockyou.txt wordlist 的情况下,我尝试了 Python 必须提供的许多编码,我发现 encoding = 'kio8_u' 可以读取文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2016-12-21
    • 1970-01-01
    相关资源
    最近更新 更多