gpt4 book ai didi

python - 如何读取包含井号的 CSV 文件?

转载 作者:太空宇宙 更新时间:2023-11-03 11:00:02 24 4
gpt4 key购买 nike

我的文件在开头有一个 NUL 字节,我很难理解“£”符号

data_initial = codecs.open(filename, "rU", "utf-16")
data = csv.DictReader((line.replace('\x00','') for line in data_initial), delimiter="\t")
for row in data:
print row

我得到错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 169: ordinal not in range(128)

顺便说一句:我是否尝试打印出这一行并不重要。我可以只打印“1”,错误仍然存​​在。我不知道为什么它说这是一个编码错误,而它可能是一个解码错误。

无论如何,我该如何处理这个问题?

最佳答案

问题几乎可以肯定是 codecs.open(filename, "rU", "utf-16") 正在以与 csv 不兼容的方式转换“£”符号:

This version of the csv module doesn’t support Unicode input. Also, there are currently some issues regarding ASCII NUL characters. Accordingly, all input should be UTF-8 or printable ASCII to be safe; see the examples in section Examples.

只需将编码类型更改为“utf-8”(假设文件中没有不兼容的符号)即可解决问题:codecs.open(filename, "rU", "utf-8")

关于python - 如何读取包含井号的 CSV 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712070/

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