当前位置: 首页 > 知识库问答 >
问题:

UnicodeDecodeError:'utf-8'编解码器无法解码位置15的字节0x96:无效的开始字节

逄征
2023-03-14
import csv
import pandas as pd
db = input("Enter the dataset name:")
table = db+".csv"
df = pd.read_csv(table)
df = df.sample(frac=1).reset_index(drop=True)
with open(table,'rb') as f:
    data = csv.reader(f)
    for row in data:
        rows = row
        break
print(rows)

我试图从csv文件中读取所有列。

错误:UnicodeDecodeError:“utf-8”编解码器无法解码位置15中的字节0x96:无效的开始字节

共有1个答案

张伯寅
2023-03-14

您需要检查您的csv文件的编码。

为此,您可以像这样使用print(f)

with open('file_name.csv') as f:
    print(f)

输出是这样的:

<_io.TextIOWrapper name='file_name.csv' mode='r' encoding='utf8'>

用这样的编码打开csv

with open(fname, "rt", encoding="utf8") as f:

如注释中所述,您的编码是cp1252

所以

with open(fname, "rt", encoding="cp1252") as f:
    ...

。读取_csv

df = pd.read_csv(table, encoding='cp1252')
 类似资料: