how to write a unicode string to a file ?

Benjamin Kaplan benjamin.kaplan at case.edu
Thu Oct 15 19:49:23 EDT 2009


On Thu, Oct 15, 2009 at 7:43 PM, Stef Mientki <stef.mientki at gmail.com> 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 ?
>
> thanks,
> Stef Mientki
>

Unicode is an abstract concept, and as such can't actually be written
to a file. To write Unicode to a file, you have to specify an encoding
so Python has actual bytes to write. If Python doesn't know what
encoding it should use, it defaults to plain ASCII which is why you
get that error.
fh.write(line.encode('UTF-8'))



More information about the Python-list mailing list