Unicode in writing to a file

Peter Otten __peter__ at web.de
Thu Apr 23 14:27:39 CEST 2009


Carbon Man wrote:

> Py 2.5
> Trying to write a string to a file.
> self.dataUpdate.write(u"\nentry."+node.tagName+ u" = " + cValue)
> cValue contains a unicode character. node.tagName is also a unicode string
> though it has no special characters in it.
> Getting the error:
> UnicodeEncodeError: 'ascii' codec can't encode character u'\x93' in
> position 22: ordinal not in range(128)

You have to decide in what encoding you want to store the data in your file.
UTF-8 is usually a good choice. Then open it with codecs.open() instead of
the built-in open():

import codecs

f = codecs.open(filename, "w", "UTF-8")
f.write(u"\nentry." + node.tagName + u" = " + cValue)

Peter




More information about the Python-list mailing list