how to write a unicode string to a file ?

Paul Boddie paul at boddie.org.uk
Fri Oct 16 08:08:50 EDT 2009


On 16 Okt, 01:49, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
>
> 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'))

Or use the codecs module to open files and streams for Unicode usage:

import codecs
fh = codecs.open("filename", "w", encoding="UTF-8")
fh.write(line)

Unicode isn't as much "abstract" as it is a definition of character
values which must be encoded in a specific way when read from or
written to a file or stream, but I think we're in agreement on this,
anyway.

Paul



More information about the Python-list mailing list