首页 > 解决方案 > 可能导致此错误的原因:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 568: invalid start byte

问题描述

我对编码和 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

什么可能导致此错误?

标签: pythonpython-3.xerror-handlingutf-8unicode-string

解决方案


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

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

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

(来自文档


推荐阅读