4
我剛離開電腦工作(使用Python 2.7),並有一個腳本,我剛剛完成轉載如下)。它在工作中運行良好,我只想添加一兩件事情。但是,我回到家,我用我的Mac的Python版本(3.2.2),我收到以下錯誤:UnicodeDecodeError:'ascii'編解碼器無法解碼0xc3中位置304中的字節:序號不在範圍內(128)
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
謝謝!這樣做的伎倆,我只需要相應地更新以下兩行:打開(名稱,「r」,編碼=「utf-8」)作爲infile: 與開放(outname,「w」,encoding =「utf -8「)作爲outfile: – user1590499 2012-08-10 22:39:27
只是爲了說明,PC上的CSV文件與通過電子郵件發送並下載到Mac上的CSV文件不同。這是否意味着Apple操作系統中的1-2行代碼使該文件與Windows操作系統的文件不同? – user1590499 2012-08-10 22:41:34
這當然可以根據這些1-2行代碼中的內容做出很大的區別。但總的來說,如果存在差異,它通常僅限於EOL字符的差異(對於unix,''\ n''對比Windows的''\ r \ n'')或編碼的差異。明確編碼應該有助於避免這個問題。 – unutbu 2012-08-11 00:49:53