UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\u8888′ in position 0: ordinal not in range(168)

來源:互聯網
上載者:User

標籤:編碼方式   nic   color   方式   write   log   ascii碼   bsp   erro   

 

 

 

在將字串寫入檔案時,執行f.write(str),後台總是報錯:UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\u8888′ in position 0: ordinal not in range(168),即ascii碼無法被轉換成unicode碼。在仔細推敲後發現,我所使用的python2.7,預設編碼是ascii格式。可以使用如下語句查看Python預設編碼格式:

>>> import sys>>> print(sys.getdefaultencoding())

 

當目標檔案為utf-8,或你要讀取的檔案為utf-8時,系統就常識以ascii格式處理,所以就錯了。

解決的辦法就是:

方式一:在python代碼中進行改變,

import sysreload(sys)sys.setdefaultencoding(‘utf-8’)

 

注意:使用此方式,有極大的可能導致print函數無法列印資料!

方式二:python安裝目錄下的lib\site-packages檔案夾下建立一個sitecustomize.py,檔案中的代碼為:

import syssys.setdefaultencoding(‘utf-8’)

 

這是比較推薦的方式。
值得欣慰的是,python3以後的版本預設編碼格式是unicode格式,就無需如此麻煩了

 

註:最終是用方式二,編碼方式改成gbk搞定

UnicodeEncodeError: ‘ascii’ codec can’t encode character u’\u8888′ in position 0: ordinal not in range(168)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.