gpt4 book ai didi

python - Unicode解码错误: 'ascii' codec can't decode byte in 0xc3 in position 304: ordinal not in range(128)

转载 作者:太空狗 更新时间:2023-10-30 02:48:41 26 4
gpt4 key购买 nike

我刚刚离开电脑工作(使用 Python 2.7)并且有一个我刚刚完成的脚本(转载如下)。它在工作中运行良好,我只想添加一两件事。但是我回到家并使用我的 Mac 版本的 Python (3.2.2),我收到以下错误:

Traceback (most recent call last):
File "/Users/Downloads/sda/alias.py", line 25, in <module>
for row_2 in in_csv:
File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 304: ordinal not in range(128)

我的代码在这里:

import csv
inname = "Fund_Aliases.csv"
outname = "output.csv"

def first_word(value):
return value.split(" ", 1)[0]

with open(inname, "r") as infile:
with open(outname, "w") as out file:
in_csv = csv.reader(infile)
out_csv = csv.writer(outfile)

column_names = next(in_csv)
out_csv.writerow(column_names)

id_index = column_names.index("id")
name_index = column_names.index("name")

try:
row_1 = next(in_csv)
written_row = False

for row_2 in in_csv:
if first_word(row_1[name_index]) == first_word(row_2[name_index]) and row_1[id_index] != row_2[id_index]:
if not written_row:
out_csv.writerow(row_1)

out_csv.writerow(row_2)
written_row = True
else:
written_row = False

row_1 = row_2
except StopIteration:
# No data rows!
pass

最佳答案

看起来 Fund_Aliases.csv 不是 ascii 文件。

根据Python3 docs :

Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:

with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)

因此请尝试指定 encoding 参数。

关于python - Unicode解码错误: 'ascii' codec can't decode byte in 0xc3 in position 304: ordinal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11909905/

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