3
votes

I have the byte-code of a png-file in a string variable. How do I write it to .png file without python trying to encode it? The string is '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\n\x00\x00\x00\x07\x08\x02\x00\x00\x00\xbe\xceK4\x00\x00\x00\x01sRGB\x00\xae\xce\x1c\xe9\x00\x00\x00\x04gAMA\x00\x00\xb1\x8f\x0b\xfca\x05\x00\x00\x00\tpHYs\x00\x00\x0e\xc3\x00\x00\x0e\xc3\x01\xc7o\xa8d\x00\x00\x00DIDAT\x18Wc\xf8\xff\xff\xff\xaf\xfd\x07\xdf[:\xbc\x95Q\x81 \xfb\xc7\xaa\xb5@q \x00I#\xcb\xc1\x11D\x11H\xfa\xdb\x94\x19hr\x10\xf4NY\x1b$\x8d\x0c\x90\x95~\xad\xacE\x97F\x03\x94H\xff\xff\x0f\x00\x1f]\xa2\x03U|Z\xa3\x00\x00\x00\x00IEND\xaeB`\x82'

edit: I feel like you might need more info on my situation: I am trying to make a little encryption program, and although it works on strings, I want to make it work for any file too. I am reading a .png file in byte-mode(which gives the string mentioned above), and after it is done being encrypted and decrypted, I have a string with the exact same content, but no way to put it back into a file.

2
open the file in binary mode (use 'wb' instead of 'w') - John La Rooy
Why aren't you using a bytes object, instead of a str, which in Python 3 is sequence of unicode code points. In other words, how did you create this str? - juanpa.arrivillaga
@JohnLaRooy almost certainly, the OP desires a bytes object that is being represented by the string. I.e. the bytes object that would be created by pre-pending that string literal with a b - juanpa.arrivillaga
Thanks John, unfortunately I have tried it, with no avail. - Jean Du Plessis
juanpa, I need to do things like finding parts of it etc., some of whick is only possible on a string. Do you know of any way to convert the string back to it's prior type? - Jean Du Plessis

2 Answers

2
votes

For python3, you have to open the file in binary write mode and encode the string to bytes:

with open('filename', 'wb') as f:
    f.write(the_string.encode())
1
votes

You could try using PyPNG, looks like a possible solution: http://pythonhosted.org/pypng/ex.html#writing

This will let you write binary to a file in python.

with open('filename', 'wb') as f:
      f.write(bytecode)