CSV to bytes to DF to bypass UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte?

CSV to bytes to DF to bypass UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte?

我有一个 csv,我之前已经毫无问题地将其读取到数据框,但现在出现以下错误: UnicodeDecodeError:'utf-8' 编解码器无法解码位置 0 中的字节 0xff:起始字节无效

df = pd.read_csv(r'\blah\blah2\csv.csv')

我试过这个:

df = pd.read_csv(r'\blah\blah2\csv.csv', encoding = 'utf-8-sig')

但这给了我这个错误:UnicodeDecodeError: 'utf-8-sig' codec can't decode byte 0xff in position 10423: invalid start byte

然后我尝试了 'utf-16',但这给了我这个错误:UnicodeError: UTF-16 stream does not start with BOM

然后我试了这个:

with open(r'\blah\blah2\csv.csv', 'rb') as f:
contents = f.read()

这很有效,但我需要那个 csv 作为数据框,所以我尝试了:

new_df = pd.DataFrame.to_string(contents)

但我得到这个错误:AttributeError: 'bytes' object has no attribute 'columns'

有人可以帮我获取数据框吗?

谢谢。

更新:

这修复了它。它将 csv 读取到没有 unicode 错误的数据框中。

df = pd.read_csv(r'\blah\blah2\csv.csv', encoding='latin1')

尝试使用以下代码找到正确的编码:

# import the chardet library
import chardet 

# use the detect method to find the encoding
# 'rb' means read in the file as binary
with open(your_file, 'rb') as file:
    print(chardet.detect(file.read()))

但是不能保证找到编码,因为上下文可能包含不同的编码或不同的语言,但是,如果它仅由 1 个代码编码,那么您可以看到。

pip(3) install chardet

如果你没有安装它

编辑1: 以下是找到正确编码的另一种方法。如果以上没有帮助,这可能会有所帮助:

from encodings.aliases import aliases
alias_values = set(aliases.values())

for value in alias_values:
    try:
        df = pd.read_csv(your_file, encoding=value) # or pd.read_excel
        print(value)
    except:
        continue

这修复了它。它将 csv 读入数据帧,没有 unicode 错误。

df = pd.read_csv(r'\blah\blah2\csv.csv', encoding='latin1')