我刚刚离开工作电脑(使用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
'\n'
与Windows的'\r\n'
之间的差异)或编码差异。明确指定编码应该有助于避免这个问题。 - unutbu