'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte


UnicodeDecodeError Traceback (most recent call last)
Input In [9], in()
1 filename = "/Users/mac/Documents/网络公开信息的使用/renkou.csv"
2 with open(filename,encoding="utf-8") as fp:
----> 3 for line in fp.readlines():
4 print(line)

File ~/opt/anaconda3/lib/python3.9/codecs.py:322, in BufferedIncrementalDecoder.decode(self, input, final)
319 def decode(self, input, final=False):
320 # decode input (taking the buffer into account)
321 data = self.buffer + input
--> 322 (result, consumed) = self._buffer_decode(data, self.errors, final)
323 # keep undecoded input until the next call
324 self.buffer = data[consumed:]

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byte

参考GPT和自己的思路:

这个错误的原因是编码格式不正确,因为在读取文件时设定的编码格式为utf-8,但是文件中存在一些无法被解码的字符,这导致了错误的发生。可能的解决方法包括更改文件编码格式为正确的utf-8格式、尝试使用其他编码格式打开文件、或者在读取文件时使用错误处理方式来处理这些无法被解码的字符。

参考GPT和自己的思路:

这个错误信息意味着在编码为 'utf-8' 的文本文件中,出现了无效的连续字节。这种情况通常发生在文件中包含不兼容编码的非ASCII字符时。为了解决这个问题,您可以尝试指定其他编码格式(例如'gbk'或'utf-16'),或者可以使用二进制模式('rb')打开文件,它将读取字节而不是字符。同时,建议您检查文件中有无乱码或者字符编码问题。

1、修改CSV文件保存为UTF-8格式
2、修改 pycharm UTF-8 编码:
进入 file > Settings,在输入框搜索 encoding。
找到 Editor > File encodings,将 IDE Encoding 和 Project Encoding 设置为utf-8。

行首加上这个

# -*- coding: utf-8 -*-

参考一下这个吧:https://blog.csdn.net/ayangann915/article/details/117523755

编码错误了,你的文件的中文编码,检查下,代码前加上codeset看看