how to write a unicode string to a file ?
somebody at somewhere.com
Fri Oct 16 22:32:40 CEST 2009
Stef Mientki wrote:
> By writing the following unicode string (I hope it can be send on this
> mailing list)
> to a file
> fh.write ( line )
> I get the following error:
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xfc' in
> position 9: ordinal not in range(128)
> How should I write such a string to a file ?
Your code fails because the unicode string denoted by the name, line, cannot
be converted to ASCII, which python silently tries to do.
Instead, use a compatible character encoding. Note the explicit conversion.
Alternatively, you can write sixteen bit unicode directly to a file:
f = codecs.open('unicodetest.txt', mode='w', encoding='utf-16')
More information about the Python-list