csv模块不支持unicode写入解决办法

csv模块不支持直接用unicode写入,没什么好方法,使用dict comprehension转换一下

# coding: utf-8 
import csv 
D
={'name':u'马克','pinyin':u'mǎkè'} 
f
= open('out.csv','wb') 
f
.write(u'\ufeff'.encode('utf8'))# BOM (optional...Excel needs it to open UTF-8 file properly) 
w
= csv.DictWriter(f,sorted(D.keys())) 
w
.writeheader() 
w
.writerow({k:v.encode('utf8')for k,v in D.items()}) 
f
.close() 

posted @ 2011-12-31 11:23  babykick  阅读(1062)  评论(0编辑  收藏  举报