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

548 Views Asked by At

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?

1

There are 1 best solutions below

0
Omer Dagry On

you can do something like this, open the file in rb mode and check if the current byte is printable, if it is print as a character if not print as hex value.

import string


with open("file name", "rb") as file:
    data = file.read()
# to print, go through the file data
for byte in data:
    # check if the byte is printable
    if chr(byte) in string.printable:
        # if it is print as character
        print(chr(byte), end="")
    else:
        # if it isn't print the hex value
        print(hex(byte), end="")