2016-01-22 63 views
0

我知道這個問題已被問及各種時間,但不知何故我沒有得到結果。Python 2.7:'ascii'編解碼器無法編碼字符u' xe9'錯誤,同時寫入文件

我正在從網頁取數據,其中包含一個字符串Elzéar。在閱讀CSV文件時,會出現問題標題中提到的錯誤。

同時產生的數據我沒有以下內容:

address = str(address).strip() 
     address = address.encode('utf8') 
     return name+','+address+','+city+','+state+','+phone+','+fax+','+pumps+','+parking+','+general+','+entertainment+','+fuel+','+resturants+','+services+','+technology+','+fuel_cards+','+credit_cards+','+permits+','+money_services+','+security+','+medical+','+longit+','+latit 

,寫它:

with open('records.csv', 'a') as csv_file: 
    print(type(data)) #prints <unicode> 
    data = data.encode('utf8')  
    csv_file.write(id+','+data+'\n') 
    status = 'OK' 
    the_file.write(ts+'\t'+url+'\t'+status+'\n') 

生成錯誤爲:

'ASCII' 編解碼器不能編碼字符U '\ xe9'位置55:序號 不在範圍內(128)

+0

使用csv軟件包 –

+0

@JavierBuzzi這是怎麼解決問題的?你能舉個例子嗎? – Volatil3

+2

不要混合使用UTF-8編碼字節的Unicode字符串。你應該將你的Unicode字符串組裝成它們的最終形式,然後編碼爲UTF-8。您應該指定您使用的Python版本(在問題標籤中),因爲Python 2和Python 3對Unicode的處理方式不同。 –

回答

1

你可以嘗試像(python2.7):

#! /usr/bin/env python 
# -*- coding: utf-8 -*- 
import codecs 
... 
with codecs.open('records.csv', 'a', encoding="utf8") as csv_file: 
    print(type(data)) #prints <unicode> 
    # because data is unicode 

    csv_file.write(unicode(id)+u','+data+u'\n') 
    status = u'OK' 
    the_file.write(unicode(ts, encoding="utf8")+u'\t'+unicode(url, encoding="utf8")+u'\t'+status+u'\n') 

主要思想是使用Unicode儘可能工作和outputing時返回STR(最好不要超過STR經營)。

+0

太棒了!像魅力一樣工作。 你打開文件爲unicode這就是爲什麼它的工作原理?你能詳細說明嗎? – Volatil3

+0

正如之前的評論所述。在做這個python的時候不要混合str和unicode,會嘗試在str和unicode之間進行一些強制轉換,這是unicode錯誤的原因。當你有最後一個Unicode時,必須指定一個合適的字符集(utf8)來輸出結果。 –

+0

又名「Unicode三明治」。解碼,編碼。在內部使用Unicodes。 –

相關問題