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

R. David Murray rdmurray at
Mon Mar 16 17:05:36 CET 2009

wallenpb at 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 "", line 19, in <module>
>     my_bmp=kohn_bmp("out.bmp",image_width,image_height,3)
>   File "C:\Python30\", line 47, in __init__
>     self.out.write("BM")          # magic number
>   File "C:\Python30\lib\", 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


R. David Murray 

More information about the Python-list mailing list