0
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**

Does anyone know why I got this error? I wanted to go through each file in my folder and see if they contained the word 'random' using my "contains" function.

  • 1
    Does this answer your question? [error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte](https://stackoverflow.com/questions/42339876/error-unicodedecodeerror-utf-8-codec-cant-decode-byte-0xff-in-position-0-in) – SuperStormer Nov 09 '20 at 03:52
  • 1
    You're trying to use `utf-8` decoding on a file that isn't actually UTF-8. Figure out the correct encoding and try again. – Mark Ransom Nov 09 '20 at 03:52

0 Answers0