2012年10月29日 星期一

[python] 編碼錯誤解決(UnicodeDecodeError)

錯誤訊息:

Traceback (most recent call last):
  File "./check_notice.py", line 243, in <module>
    file.save('Check_Legal_Notice_Report.xls')
  File "/usr/local/lib/python2.7/dist-packages/xlwt/Workbook.py", line 643, in save
    doc.save(filename, self.get_biff_data())
  File "/usr/local/lib/python2.7/dist-packages/xlwt/Workbook.py", line 618, in get_biff_data
    shared_str_table   = self.__sst_rec()
  File "/usr/local/lib/python2.7/dist-packages/xlwt/Workbook.py", line 580, in __sst_rec
    return self.__sst.get_biff_record()
  File "/usr/local/lib/python2.7/dist-packages/xlwt/BIFFRecords.py", line 77, in get_biff_record
    self._add_to_sst(s)
  File "/usr/local/lib/python2.7/dist-packages/xlwt/BIFFRecords.py", line 92, in _add_to_sst
    u_str = upack2(s, self.encoding)
  File "/usr/local/lib/python2.7/dist-packages/xlwt/UnicodeUtils.py", line 50, in upack2
    us = unicode(s, encoding)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 40: ordinal not in range(128)

--

此為編碼錯誤(UnicodeDecodeError)

Python內部使用unicode編碼
在做編碼轉換時,需先將其他解碼(decode)成unicode
再從unicode編碼(encode)成另一種編碼

Ex1:
print a.encode('utf-8')

Ex2:
sheet.write(row,col,data.encode('utf-8'))

沒有留言:

張貼留言