简体   繁体   中英

Problems read files in python:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd5 in position 168: invalid continuation byte

I try to open the text file and it does not work

with open('quiz.txt') as f:
    lines = f.readlines()
Traceback (most recent call last):
  File "<pyshell#35>", line 2, in <module>
    lines=f.readlines()
  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 0xd5 in position 168: invalid continuation byte

在此处输入图像描述

Invalid continuation byte = not unicode = probably a binary file.

with open('quiz.txt', 'rb') as f:
    lines = f.readlines()

will open the file in bytes mode.

Another possibility is that you are executing this in your shell, and the program looks for stuff only in the working directory.

import os
os.chdir('/path/to/your/file/excluding/file/name')
with open('quiz.txt', 'rb') as f:
    lines = f.readlines()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM