Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

python - Writing unicode data in csv

I know similar kind of question has been asked many times but seriously i have not been able to properly implement the csv writer which writes properly in csv (it shows garbage).

I am trying to use UnicodeWriter as mention in official docs .

ff = open('a.csv', 'w')
writer = UnicodeWriter(ff)
st = unicode('Displaygr??en', 'utf-8') #gives (u'Displaygrxf6xdfen', 'utf-8')
writer.writerow([st])

This does not give me any decoding or encoding error. But it writes the word Displaygr??en as Displaygr????en which is not good. Can any one help me what i am doing wrong here??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are writing a file in UTF-8 format, but you don't indicate that into your csv file.

You should write the UTF-8 header at the beginning of the file. Add this:

ff = open('a.csv', 'w')
ff.write(codecs.BOM_UTF8)

And your csv file should open correctly after that with the program trying to read it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...