from sys import * class pgm: def __init__(self, magic_num='',width=0,height=0,max_grey=0,fname='',data=[]): #initialize a blank pgm. self.width=width self.height=height self.max_grey=max_grey self.data=data self.magic_num=magic_num self.tdata = [] def open_pgm(self,path): #get all the lines of the file IFile = open(path,"rb") print "getting data" try: self.magic_num = IFile.readline().strip() tmp_holder = IFile.readline().strip().split() self.width = int(tmp_holder[0]) self.height = int(tmp_holder[1]) self.max_grey = int(IFile.readline().strip()) except: print "invalid header, expected:" print "P2\nxxx xxx\n255\n" print "found:" print str(self.magic_num) + "\n" + str(self.width) + " " +str(self.height) print str(self.max_grey) for line in IFile: tmp_dat = IFile.readline().strip().split() print tmp_dat try: self.data.append(tmp_dat) except: print "'data.append(tmp_dat)' failed" def toString(self): print self.magic_num print str(self.width) + " " + str(self.height) print self.max_grey print "" #print self.data def toFile(self, path): OFile = open(path,"w") OFile.write(self.magic_num + "\n") OFile.write(str(self.width) + " " + str(self.height) + "\n") OFile.write(str(self.max_grey) + "\n") for i in self.data: for j in i: OFile.write(j + " ") OFile.write("\n") OFile.close() #EOF user@host$head $INPUTFILE P2 300 202 255 104 106 107 107 106 106 107 108 107 107 107 107 108 108 108 108 109 109 109 109 109 109 111 112 110 111 111 111 110 110 111 112 112 112 112 112 113 113 113 113 114 115 115 115 116 116 115 115 114 116 116 115 115 116 116 115 117 117 117 117 116 116 117 117 118 118 118 118 118 119 119 119 119 119 119 120 120 121 120 120 120 121 122 122 user@host$head $OUTPUTFILE P2 300 202 255 133 134 134 134 135 134 133 133 133 134 135 134 134 134 134 133 133 133 134 134 134 134 134 133 133 133 134 134 134 135 135 134 134 134 134 135 135 134 134 133 133 134 134 134 133 133 133 134 134 134 134 133 133 133 133 133 133 133 133 132 133 133 132 133 135 135 134 134 134 134 134 134 134 134