我试图在python中手动打开和解释一个P6 ppm图像文件。一个ppm的p6文件在开始时有几行普通的ascii,然后是二进制的实际图像数据(这与ppm p3文件相反,后者都是纯文本)。
我已经找到了一些可以读取ppm文件的模块(opencv,numpy),但我真的很想手动读取它(特别是因为ppm应该是一种相当简单的图像格式)。
当我试图打开和读取文件时,无论我使用open("image.ppm", "rb")
还是open("image.ppm", "r")
,都会遇到错误,因为这两种方法都需要一个文件,要么是二进制文件,要么是纯文本文件。
因此,更广泛地说:在python中是否有一种容易打开混合二进制/文本文件的方法?
发布于 2022-11-08 22:10:06
您可以这样做,在rb
模式下对文件进行rb
,并检查当前的byte
是否为printable
,如果不是print
为hex value
,则为print
作为character
。
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="")
https://stackoverflow.com/questions/74367573
复制相似问题