I’m currently trying to save and load data from a PNMImage into a file that contains other data. As per usual, I’m doing this via my “GameSaver” module–but I’m hitting a problem.
From what I’ve gathered, the problem seems to be something like this:
As part of handling strings, GameSaver converts them via a call to “encode(‘unicode_escape’)”. It then later decodes them via “decode(‘utf-8’)” to get a string-object again before writing that out.
It’s been a while since I implemented this, but if I recall correctly, this was implemented in order that strings could be saved without having to worry about special characters. And indeed, for normal strings, it seems to work as intended.
The problem comes when I try to save something that is already a “bytes” object–in particular, the “bytes” object acquired from the “getData()” method of a StringStream that has just been written to by PNMImage. This goes through the system, hits the call to “decode”, and trips over it with the following error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte
After a bit of searching around, I tried just catching and ignoring the error. The “write” method of a file-object won’t accept a “bytes” object, however, and simply casting it to a “str” results in something that isn’t successfully loaded by a new PNMImage (reading it via a StringStream).
I’m really not sure of what to do here. Any suggestions?
(I could probably just save the PNMImage to a separate file, but I’d rather not do that in this case.)