[Tutor] Find multiple lines in a file

Bill Burns billburns at pennswoods.net
Wed Nov 9 05:07:44 CET 2005


I have a PostScript file which contains the following lines (the numbers
are for reference only and are *not* in the file):

1 <<
2   /Policies <<
3     /PageSize 3
4   >>
5 >> setpagedevice

These lines never change and are always formatted like this (at least in
the PostScript files that I'm generating with tiff2ps).

I want to open the the file and read it, find these five lines and then
replace the lines with something different.

I understand how to open and read the file. I have no problems finding
and changing a *single* line, but I can not figure out how to find the
*multiple* lines (and put them into one variable).

Here's some code I'm using to replace just a *single* line in the
PostScript file (Note - I'm changing the BoundingBox which is in the
same file, but is *not* one of the five lines above).

<code>
import fileinput

class ChangeBBox:
     pass

     def getBBox(self, filename):
             f = open(filename, "rb")
             buffer = 1000
             tmp = f.readlines(buffer)
             f.close()
             for line in tmp:
                 if line.startswith('%%BoundingBox:'):
                     return line.strip()

     def modifyBBox(self, filename):
         old = self.getBBox(filename)
         new = '%%BoundingBox: 0 0 1296 1728'
         for line in fileinput.input(filename, inplace=1):
             print line.replace(old, new),
</code>

The above code uses the fileinput module which makes it really nice for
modifying a file 'inplace'. I use the code like this

c = ChangeBBox()
c.modifyBBox(somePostScriptFile.ps)

and it works great, but it's really simple because it only has to modify
*one* line.

Can anyone offer suggestions on how to find all five lines? I don't
think I'll have a problem replacing the lines, it's just getting them
all into one variable that stumping me :-)

Thanks,

Bill


More information about the Tutor mailing list