python - CSV, DictWriter, unicode and utf-8 -


I'm having trouble with dictator and non-ASCII characters. A small version of my problem:

  #! / Usr / bin / env dragon # - * - coding: utf-8 - * - import codec import csv f = codecs.open ("test.cv", 'w', 'utf-8') author = csv.DictWriter (F, ['field1'], delimiter = '\ t') writer.writerow ({'field1': u'a'.encode ('utf-8')}) f.close ()  < / Pre> 

This traceback gives:

  traceback (most recent call final): File "test .p", in line 10, in the & lt; Module & gt; Author. Author ({'Field1': u'a'.encode ('utf-8')} File "/ Library / Framework / Python. Framework / Version-2.5 / lib / python2.5/csv.py", line 124, author in return to self. Author. Author (auto._dict_to_list (rowdict)) file "/ Library / Firmwork / Python.Framework / version-2.5 / lib / python2.5 / codecs.py", line 638, write itself .writer.write (data) File "/ library / framework / Python.framework / Versions / 2.5 / lib / python2.5 / codecs.py", line 303, data to write, consumption = self.encode (object, self. Errors) Unicodecode error: 'ASCI 'Can not decode the byte 0xc3 in the codec condition 0: In the serial no category (128)  

I have lost a bit because Dic TWriter should be able to work with UTF-8 which I have read in the document.

You write the object you received with codecs.open A Unicode string wants> method - this whole thing is csv.DictWriter Of course that method is telling the exception instead of the utf8-encoded byte string .

f to build f = open ("test.csv", 'wb') ( codecs from the picture) Take out) and things should work properly.


Comments