Problems with struct.pack()

Robert Dailey rcdailey at gmail.com
Thu Oct 11 17:45:26 CEST 2007


On 10/11/07, Carsten Haese <carsten at uniqsys.com> wrote:
>
> This is much clearer, and it explains why you need to mix arbitrary binary
> data with unicode text. Because of this mixing, as you have surmised,
> you're
> going to have to treat the file as a binary file in Python. In other
> words,
> don't open the file with the codecs module and do the encoding yourself,
> like so:
>
> mystring = u"Hello World"
> file = open( "somefile.txt", "wb" )
> file.write( struct.pack ( "I", len(mystring) ) )
> file.write( mystring.encode("utf-16-le") )
>
> (Note that I've guessed that you want little-endian byte-order in the
> encoding. Without that indication, encode() would put a byte order mark at
> the
> beginning of the string, which you probably don't want.)
>
> Hope this helps,
>
> Carsten.
>
>

What if 'mystring' has been encoded to "utf-8"?

mystring = u"Hello World"
mystring = mystring.encode( "utf-8" )

So far the code above doesn't seem to work with this.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20071011/7fdb0480/attachment.html>


More information about the Python-list mailing list