【问题标题】:What could cause this error : UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte可能导致此错误的原因:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte
【发布时间】:2020-05-03 03:07:09
【问题描述】:

我对编码和 python 很陌生,所以我真的对这个错误感到困惑。这是我的练习代码,我需要在包含多个文件的目录中找到最常用的单词

import pathlib

directory = pathlib.Path('/Users/k/files/Code/exo')

stats ={}

for path in directory.iterdir():
    file = open(str(path))
    text = file.read().lower()

    punctuation  = (";", ".")
    for mark in punctuation:
        text = text.replace(mark, "")


    for word in text.split():
        if word in stats:

            stats[word] = stats[word] + 1
        else:
            stats[word] = 1

most_used_word = None
score_max = 0
for word, score in stats.items():
    if score > score_max:
        score_max = score
        most_used_word = word

print(word,"The most used word is : ", score_max) 

这就是我得到的

Traceback (most recent call last):
  File "test.py", line 9, in <module>
    text = file.read().lower()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py", line 322, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte

什么可能导致这个错误?

【问题讨论】:

标签: python python-3.x error-handling utf-8 unicode-string


【解决方案1】:

您的文件可能包含非 ascii 字符,因此您必须对它们进行解码才能使 UnicodeDecodeError 消失。您可以尝试在“rb”模式下阅读,如下所示:

file = open(str(path), 'rb')

在 Windows 上,附加到模式的 'b' 以二进制模式打开文件,因此还有 'rb'、'wb' 和 'r+b' 等模式。 Windows 上的 Python 区分了文本文件和二进制文件;读取或写入数据时,文本文件中的行尾字符会自动稍作更改。这种对文件数据的幕后修改对于 ASCII 文本文件来说很好,但它会破坏像 JPEG 或 EXE 文件中的二进制数据。在读写此类文件时要非常小心使用二进制模式。在 Unix 上,将 'b' 附加到模式并没有什么坏处,因此您可以独立于平台使用它来处理所有二进制文件。

(来自docs

【讨论】:

    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 2022-09-26
    • 2020-01-31
    相关资源
    最近更新 更多