编写简单代码时,我不断收到“ UnicodeDecodeError:'utf-8'编解码器无法解码位置3131:无效的起始字节的字节0x80”错误

时间:2020-11-09 03:46:59

标签: python utf-8 decoding

import os

def contains(filename, pattern):
    with open(filename) as file:
        for line in file:
            if pattern in line:
                return True
    return False

for filename in os.listdir('/Users/DanielKapri/Desktop/Python'):
    if contains(filename, 'random'):
        print(filename, 'contains random')

Prints:

Traceback (most recent call last):
  File "/Users/DanielKapri/Desktop/Python/contains.py", line 11, in <module>
    if contains(filename, 'random'):
  File "/Users/DanielKapri/Desktop/Python/contains.py", line 5, in contains
    for line in file:
  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 0x80 in position 3131: invalid start byte**

有人知道我为什么会收到此错误吗? 我想浏览文件夹中的每个文件,然后使用“包含”功能查看它们是否包含“随机”一词。

0 个答案:

没有答案