StringIO + unicode

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Tue Mar 25 12:06:22 EDT 2008


En Tue, 25 Mar 2008 06:26:04 -0300, Laszlo Nagy <gandalf at shopzeus.com>  
escribió:

> Is there a standard "in-memory file" interface for reading/writting
> unicode stings? Something like StringIO.
>
> E.g. this would be possible:
>
> - create UnicodeStringIO
> - write unicode strings into it
> - wite data (binary) string of UnicodeStringIO into a file ('wb' mode)

No. Files contain bytes, not characters; you have to encode the Unicode  
object when writing to a file (or StringIO object).
As Diez suggested, use the codecs classes:

py> import codecs
py> from StringIO import StringIO
py> orig_file = StringIO()
py> wrapped_file = codecs.getwriter('hex')(orig_file)
py> wrapped_file.write("Hello world!")
py> wrapped_file.getvalue()
48656c6c6f20776f726c6421

See http://docs.python.org/lib/stream-writer-objects.html

-- 
Gabriel Genellina




More information about the Python-list mailing list