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