Aamir Rind
Aamir Rind

Reputation: 39709

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'Displaygr\xf6\xdfen', '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??

Upvotes: 4

Views: 9412

Answers (2)

Zeugma
Zeugma

Reputation: 32125

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.

Upvotes: 6

dav1d
dav1d

Reputation: 6055

Opening the file with codecs.open should fix it.

Upvotes: 0

Related Questions