Home:ALL Converter>Simple way to read a mixed binary / ascii file in python?

Simple way to read a mixed binary / ascii file in python?

Ask Time:2022-11-09T05:52:50         Author:Sam van Kesteren

Json Formatter

I'm trying to open and interpret a P6 ppm image file by hand in python. A ppm p6 file has a few lines of plain ascii at the start, followed by the actual image data in binary (this in contrast to a ppm p3 file, which is all plain text).

I've found a few modules that can read ppm files (opencv, numpy), but I'd really like to try to do it by hand (especially since ppm is supposed to be a fairly simple image format).

When I try to open and read the file I encounter errors, whether I use open("image.ppm", "rb") or open("image.ppm", "r"), because these both expect a file that's either just binary or just plaintext.

So, more broadly: is there an easy to way to open files that are mixed binary/text in python?

Author:Sam van Kesteren,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/74367573/simple-way-to-read-a-mixed-binary-ascii-file-in-python
yy