how to write a unicode string to a file ?

Stephen Fairchild somebody at somewhere.com
Fri Oct 16 22:32:40 CEST 2009


Stef Mientki wrote:

> hello,
> 
> By writing the following unicode string (I hope it can be send on this
> mailing list)
> 
>     Bücken
> 
> 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.

    fh.write(line.encode('utf-8'))

Alternatively, you can write sixteen bit unicode directly to a file:

    import codecs

    f = codecs.open('unicodetest.txt', mode='w', encoding='utf-16')
    f.write(u'Hello world\n')
    f.close()
-- 
Stephen Fairchild



More information about the Python-list mailing list