error writing str to binary stream - fails in Python 3.0.1, works in 2.x

R. David Murray rdmurray at bitdance.com
Mon Mar 16 18:29:32 EDT 2009


wallenpb at gmail.com wrote:
> On Mar 16, 4:10 pm, Benjamin Peterson <benja... at python.org> wrote:
> >  <wallenpb <at> gmail.com> writes:
> >
> >
> >
> > > self.out.write(b'BM') worked beautifully.  Now I also have a similar
> > > issue, for instance:
> > > self.out.write("%c" % y) is also giving me the same error as the other
> > > statement did.
> > > I tried self.out.write(bytes("%c" %y),encoding=utf-8) in an attempt to
> > > convert to bytes, which it did, but not binary.  How do I affect
> > > self.out.write("%c" % y) to write out as a binary byte steam?  I also
> > > tried self.out.write(b"%c" % y), but b was an illegal operator in when
> > > used that way.
> > > It is also supposed to be data being written to the .bmp file. --Bill
> >
> > Are you writing to sys.stdout? If so, use sys.stdout.buffer.write(b'some
> > bytes'). If you're writing to a file, you have to open it in binary mode like
> > this: open("someimage.bmp", "wb")
> 
> Yes, I am writing to a file.  That portion is correct and goes like
> this:
>
> self.out=open(filename,"wb")
>     self.out.write(b"BM")          # This line works thanks to advice given
>                                    # in previous reply
> 
> However, here is some more code that is not working and the error it
> gives:
>
> def write_int(self,n):
>     str_out='%c%c%c%c' % ((n&255),(n>>8)&255,(n>>16)&255,(n>>24)&255)
>     self.out.write(str_out) 
>
> this is line 29, does not work - not
> sure how to get this complex str converted over to binary bytes to
> write to bmp file.

(I reformatted your message slightly to make the code block stand out more.)

A byte array is an array of bytes, and it understands integers as input.
Check out the PEP (the official docs leave some things out):

    http://www.python.org/dev/peps/pep-0358/

Here is some example code that works:

    out=open('temp', "wb")
    out.write(b"BM")

    def write_int(out, n):
        bytesout=bytes(([n&255), (n>>8)&255, (n>>16)&255, (n>>24)&255])
        out.write(bytesout)   

    write_int(out, 125)

--
R. David Murray           http://www.bitdance.com




More information about the Python-list mailing list