kich
kich

Reputation: 764

problems with handling unicode characters in python

I wrote the below code for writing the contents to the file,

   with codecs.open(name,"a","utf8") as myfile:
         myfile.write(str(eachrecord[1]).encode('utf8'))
         myfile.write(" ")
         myfile.write(str(eachrecord[0]).encode('utf8'))
         myfile.write("\n")`

The above code does not work properly when writing uni-code characters....Even though i am using codecs and doing the encoding. I keep getting the error

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 6: ordinal not in range(128)

Can anyone see where i am doing it wrong ?

Edit:

with codecs.open(name,"a","utf8") as myfile:
                    myfile.write(unicode(eachrecord[1]))
                    myfile.write(" ")
                    myfile.write(unicode(eachrecord[0]))
                    myfile.write("\n")

This worked..Thanks for all the quick comments and answers..that really helps ..I did not realize that python has 'unicode' option until you guys told me

Upvotes: 1

Views: 343

Answers (1)

Avaris
Avaris

Reputation: 36715

Remove the str() calls. They are doing an implicit encoding with the default encoding (ascii in this case).

Upvotes: 2

Related Questions