How to save a binary file?

MRAB python at
Wed Oct 6 19:45:14 CEST 2010

On 06/10/2010 15:25, hidura at wrote:
> When you put the 'wb' extension you have to pass a Encode the string
> Python does not accept a string on a wb file, Python3
You are using Python 3 and type(str) returns "<class 'type'>"?

Binary data in Python 3 should be an instance of the 'bytes' class, not
an instance of the 'str' class.

If you can't fix that, you could turn the string into bytes using:

     data = bytes(ord(c) for c in str)

or by carefully choosing an encoding which would give the same result:

     data = str.encode('latin-1')

Then you can save it:

     s = open('/home/hidura/test.jpeg', 'wb')

I asked you to look at the result of repr so that you could see more
clearly what the data actually looked like, an instance of str or an
instance of bytes.

More information about the Python-list mailing list