2014-03-13 39 views
8

我從來沒有處理過編碼和解碼字符串,所以我是這方面的新手。當我嘗試使用Python中的file.write將從另一個文件讀取的內容寫入臨時文件時,我收到一個UnicodeEncodeError。我收到以下錯誤:在Python中使用file.write寫入文件時出錯。 UnicodeEncodeError

UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 41333: ordinal not in range(128) 

這是我在我的代碼中所做的。我正在閱讀一個XML文件並從「mydata」標籤中獲取文本。然後,我通過MYDATA迭代尋找CDATA

parser = etree.XMLParser(strip_cdata=False) 
    root = etree.parse(myfile.xml, parser) 
    data = root.findall('./mydata') 
    # iterate through list to find text (lua code) contained in elements containing CDATA 
    for item in myData: 
     myCode = item.text 

    # Write myCode to a temporary file. 
    tempDirectory = tempfile.mkdtemp(suffix="", prefix="TEST_THIS_") 
    file = open(tempDirectory + os.path.sep + "myCode.lua", "w") 

    file.write(myCode + "\n") 
    file.close() 

它無法與UnicodeEncodeError時,我打下面一行:

file.write(myCode + "\n") 

我應該如何正確編碼和解碼呢?

+0

的Python版本? – metatoaster

+0

使用Python 2.7 – user2643864

+0

寫入文件時可能出現[UnicodeEncodeError]重複(http://stackoverflow.com/questions/6939692/unicodeencodeerror-when-writing-to-a-file) –

回答

16

Python2.7的open函數不能透明地處理像python3那樣的Unicode字符。有extensive documentation on this,但如果你想寫unicode字符串的情況下直接進行解碼,從而,你可以試試這個

>>> import codecs 
>>> f = codecs.open(filename, 'w', encoding='utf8') 
>>> f.write(u'\u201c') 

爲了便於比較,這是錯誤是如何發生的

>>> f = open(filename, 'w') 
>>> f.write(u'\u201c') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128) 
+0

工作很好。正是我需要的。謝謝。 – user2643864