所以我在导入 csv 文件时遇到了这个问题(它与我的 Python 3 文件位于同一目录中)

So I got this problem while importing a csv file (It is in the same directory as my Python 3 file)

以下代码行:

file = pd.read_csv('okstodo.csv')

给我以下错误:


UnicodeDecodeError Traceback (most recent call last) pandas/_libs/parsers.pyx 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

试试这个。

data = pd.read_csv("okstodo.csv", encoding = 'unicode_escape', engine ='python')

还要检查 standard-encodings 在 pandas 中的使用。

read_csv 采用编码选项来处理不同格式的文件。我主要使用 read_csv('file', encoding = "ISO-8859-1"), 或者 encoding = "utf-8" 用于阅读,通常使用 utf-8 用于 to_csv.

您还可以使用多个别名选项之一,例如 'latin' 而不是 'ISO-8859-1'(请参阅 python 文档,以及您可能遇到的许多其他编码)。

查看相关 Pandas 文档、python 关于 csv 文件的文档示例,以及此处关于 SO 的大量相关问题。一个很好的背景资源是 What every developer should know about unicode and character sets。

要检测编码(假设文件包含非 ascii 字符),您可以使用 enca(参见手册页)或 file -i (linux) 或 file -I (osx )(参见手册页)。