我有一個使用xlwt/xlrd來處理excel文件的python腳本。在我的腳本的開始,我有以下代碼:在Python中正確解碼unicode時遇到問題
#if you got a csv in parameters, convert it to an xls file
if '.csv' in sys.argv[1]:
#name of new file after conversion is finished
name = sys.argv[1]
csvfile = open(sys.argv[1], 'rb')
try:
#extract data from .csv
csvReader = csv.reader(csvfile, delimiter=' ', quotechar='|')
csvData = list(csv.reader(open(name, 'rb')))
# write to a xls file
outFile = xlwt.Wrokbook()
newSheet = outFile.add_sheet('Sheet 1')
# traverse over 2d array to write each individual cell
for row in range(len(csvData)):
for col in range(len(csvData[0])):
newSheet.write(row, col, csvData[row][col].encode('utf8'))
name = name[:-4] + ".xls" #change extension of file
outFile.save(name)
wb = open_workbook(name)
finally:
csvfile.close()
這給行outFile.save(名)錯誤
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 44: ordinal not in range(128)
我有唯一有用的東西發現到目前爲止,以幫助這是UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1,但我的終端使用utf8作爲其編碼。
編輯: 完全忘了提這個,很抱歉。
我相信帶有.encode的行會以某種方式引起錯誤,但我無法想象如何。我原本沒有.encode,然後我添加了.encode('utf8'),也嘗試過.encode('utf-8')和unicode(字符串'utf8')。我不知道還有什麼可以嘗試解決這個問題。編號: 我試過Brian的建議沒有用。此外,我嘗試了codecs.open建議,並嘗試在創建工作簿時指定編碼。這些事情都沒有改變錯誤。我試過的唯一一個改變錯誤的地方就是在newSheet.write中添加了.encode。沒有它,我得到:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 44: ordinal no in range(128)
而且用它我得到:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 44: ordinal not in range(128)
'csvData [行] [COL] .decode( 'utf-8')'也許?假設是拋出錯誤的那一行 –
什麼版本的python? – Brian
@Brian Python 2.7 – avorum