4
votes

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??

2
Are you sure that you are viewing a.csv with the right encoding? - Don
No i am not sure, i am just opening that csv file. How to do that? - Aamir Adnan
I have used text import wizard of excel and i defined utf-8 encoding there, the data is shown correct. Can we define encoding of csv file in code so that i do not have to use this wizard? Also if i use codecs.open and then i try to write unicode data then it will cause problems which is mention here also stackoverflow.com/questions/3085263/… - Aamir Adnan
There doesn't seem to be anything wrong with the file's encoding. If you're displaying the file somewhere that isn't set to unicode you'll get that error though. for example, on a Linux box if I try to cat a file with non-ASCII characters in it on a terminal when my locale is set to for example ASCII, I'll get garbled text like that. - JosefAssad
In most editors, you can set the 'encoding' in 'File' or 'View' menu. E.g. in Scite you can choose utf-8 from File->Encoding. - Don

2 Answers

6
votes

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.

0
votes

Opening the file with codecs.open should fix it.