The issue you are facing is most likely due to character encoding issues. If you store the received data in a variable, Python will interpret the \xNN
values as characters and as such they need to be encoded before they can be saved to disk.
The choice of encoding will write different data. Normally you would like to store your data as "utf-8" (standard in Linux and most portable) or perhaps in some kind of windows format, e.g. "windows-1252". In this particular case, though, we are not dealing with text or symbols, but rather with raw data. Therefore neither of the codings above will give a correct, working output. What is needed, is rather raw_unicode_escape
since this will encode the characters without modifying the underlying bit patterns.
Thus, to store the image, we need something like:
# Triple quote string, as it may contain both string markers ('")
img = """\x89PNG\r\n\x1a\n\x00\x00 ... \x00\x00\x00IEND\xaeB`\x82"""
with open("image.png", "wb") as f:
f.write(img.encode("raw_unicode_escape")
I ran this on my computer and got an image displaying a little man in front of a house.