Read and Write CSV files including unicode with Python 2.7 -


i new python, , have question how use python read , write csv files. file contains germany, french, etc. according code, files can read correctly in python, when write new csv file, unicode becomes strange characters.

the data like: enter image description here

and code is:

import csv  f=open('xxx.csv','rb') reader=csv.reader(f)  wt=open('lll.csv','wb') writer=csv.writer(wt,quoting=csv.quote_all)  wt.close() f.close() 

and result like: enter image description here

would please tell me should solve problem? thank much!

make sure encode , decode appropriate.

this example roundtrip example text in utf-8 csv file , out demonstrate:

# -*- coding: utf-8 -*- import csv  tests={'german': [u'straße',u'auslösen',u'zerstören'],         'french': [u'français',u'américaine',u'épais'],         'chinese': [u'中國的',u'英語',u'美國人']}  open('/tmp/utf.csv','w') fout:     writer=csv.writer(fout)         writer.writerows([tests.keys()])     row in zip(*tests.values()):         row=[s.encode('utf-8') s in row]         writer.writerows([row])  open('/tmp/utf.csv','r') fin:     reader=csv.reader(fin)     row in reader:         temp=list(row)         fmt=u'{:<15}'*len(temp)         print fmt.format(*[s.decode('utf-8') s in temp]) 

prints:

german         chinese        french          straße         中國的            français        auslösen       英語             américaine      zerstören      美國人            épais   

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -