gpt4 book ai didi

Python 3 CSV 文件给出 UnicodeDecodeError : 'utf-8' codec can't decode byte error when I print

转载 作者:IT老高 更新时间:2023-10-28 20:49:21 25 4
gpt4 key购买 nike

我在 Python 3 中有以下代码,用于打印 csv 文件中的每一行。

import csv
with open('my_file.csv', 'r', newline='') as csvfile:
lines = csv.reader(csvfile, delimiter = ',', quotechar = '|')
for line in lines:
print(' '.join(line))

但是当我运行它时,它给了我这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte

我查看了 csv 文件,结果发现如果我取出一个 ñ(顶部有波浪号的小 n),每一行都可以打印出来。

我的问题是我已经查看了一堆不同的解决方案来解决类似的问题,但我仍然不知道如何解决这个问题,解码/编码什么等。只需取出数据中的 ñ 字符即可不是一个选择。

最佳答案

我们知道该文件包含字节 b'\x96',因为它在错误消息中被提及:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 7386: invalid start byte

现在我们可以编写一个小脚本来查看是否有任何编码将 b'\x96' 解码为 ñ:

import pkgutil
import encodings
import os

def all_encodings():
modnames = set([modname for importer, modname, ispkg in pkgutil.walk_packages(
path=[os.path.dirname(encodings.__file__)], prefix='')])
aliases = set(encodings.aliases.aliases.values())
return modnames.union(aliases)

text = b'\x96'
for enc in all_encodings():
try:
msg = text.decode(enc)
except Exception:
continue
if msg == 'ñ':
print('Decoding {t} with {enc} is {m}'.format(t=text, enc=enc, m=msg))

产生

Decoding b'\x96' with mac_roman is ñ
Decoding b'\x96' with mac_farsi is ñ
Decoding b'\x96' with mac_croatian is ñ
Decoding b'\x96' with mac_arabic is ñ
Decoding b'\x96' with mac_romanian is ñ
Decoding b'\x96' with mac_iceland is ñ
Decoding b'\x96' with mac_turkish is ñ

因此,请尝试更改

with open('my_file.csv', 'r', newline='') as csvfile:

到其中一种编码,例如:

with open('my_file.csv', 'r', encoding='mac_roman', newline='') as csvfile:

关于Python 3 CSV 文件给出 UnicodeDecodeError : 'utf-8' codec can't decode byte error when I print,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com