error writing str to binary stream - fails in Python 3.0.1, works in 2.x
wallenpb at gmail.com
wallenpb at gmail.com
Mon Mar 16 16:25:36 EDT 2009
On Mar 16, 11:05 am, "R. David Murray" <rdmur... at bitdance.com> wrote:
> walle... at gmail.com wrote:
> > I am working with a bit of code that works ok in Python 2.x (tested
> > fine in 2.5.4 and 2.6.1) but fails in 3.0.1.
> > The code opens a file for binary output to witht the objective to
> > produce a .bmp graphics file. The code below illustrates the first of
> > several like errors when a str object is attempted to be written to
> > the binary file. From what I have seen, this was a fairly common
> > technique prior to 3.0.1 being released so I am assuming the type
> > checking is tighter with the new version. What is the proper way of
> > doing this now, or the work around? Any help appreciated. -- Bill
>
> > the code:
> > -----------------------------------
> > self.out=open(filename,"wb")
> > self.out.write("BM") # magic number
>
> > This the is the error output from Python:
> > ------------------------------------
> > Traceback (most recent call last):
> > File "py_mandel.py", line 19, in <module>
> > my_bmp=kohn_bmp("out.bmp",image_width,image_height,3)
> > File "C:\Python30\py_kohn_bmp.py", line 47, in __init__
> > self.out.write("BM") # magic number
> > File "C:\Python30\lib\io.py", line 1038, in write
> > raise TypeError("can't write str to binary stream")
> > TypeError: can't write str to binary stream
>
> In 3.x the 'str' type is unicode. If you want to work with binary byte
> streams, you want to use the 'bytes' type. Bytes contstants are
> written with a leading 'b', so the code snipped above would become
>
> self.out.write(b'BM')
>
> --
> R. David Murray http://www.bitdance.com
David,
Thanks for the assist. One more question, please.
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
More information about the Python-list
mailing list