小编Clo*_*One的帖子

Python将文件读入unicode字符串

我在理解在 Python 中处理 unicode 字符串的正确方法时遇到了一些麻烦。我已经阅读了很多关于它的问题,但仍然不清楚在读写文件时应该怎么做才能避免出现问题。

我的目标是有效地逐行读取一些巨大的(最多 7GB)文件。我是用简单的方法完成的,with open(filename) as f:但最终在 ASCII 解码中出现错误。

然后我读到正确的做法是写:

with codecs.open(filename, 'r', encoding='utf-8') as logfile:
Run Code Online (Sandbox Code Playgroud)

然而,这最终是:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x88 in position 13: invalid start byte
Run Code Online (Sandbox Code Playgroud)

坦率地说,我不明白为什么会引发此异常。

我找到了一个可行的解决方案:

with open(filename) as f:
    for line in logfile:
        line = unicode(line, errors='ignore')
Run Code Online (Sandbox Code Playgroud)

但这种方法最终非常缓慢。因此我的问题是:

有没有正确的方法来做到这一点,最快的方法是什么?谢谢

python string unicode file

3
推荐指数
1
解决办法
2545
查看次数

标签 统计

file ×1

python ×1

string ×1

unicode ×1