[Tutor] find and replace relative to an nearby search string in a file

Pete O'Connell pedrooconnell at gmail.com
Mon Jul 13 07:07:46 CEST 2009


Hi, I am trying to do a find and replace in a text file (a nuke script).
Here are a couple excerpts from the file that demonstrate what I want to do.
I am always looking for the line " name Write1" as my starting point. In the
first example below, I want to replace the path, which is 2 lines above it.
I have made a basic script to do that and it works fine. The problem I am
having is when the number of lines between " name Write1" and the path above
it is not 1, my script breaks. I'm not sure how to say in python "when you
find the line " name Write1", go back line by line until you find a line
that begins with  " file /Volumes/" and then assign a new variable to the
path on that line".
At the very bottom of this post I have included what I have so far (The
script which works but breaks). Any help would be greatly appreciated.
Pete



Write {
 file /Volumes/raid0/Z353_002_comp_v27.%04d.cin
 file_type cin
 name Write1
 xpos 13762
 ypos -364
}



Write {
 file /Volumes/raid0/Z353_002_comp_v04.%04d.exr
 colorspace linear
 raw true
 file_type exr
 name Write1
 selected true
 xpos -487
 ypos -155
}

# This is the basic script
import re

theFile = open('/Volumes/raid0/Z353_001_comp_v05.nk',"r")

theNukeScriptText = theFile.read()
theFile.close()



#p = re.compile('.+_comp_v\d\d.%04d.cin\n file_type cin\n name Write1')
p = re.compile(r'.+_comp_v\d\d.%04d.cin\n.+\n name Write1')
m =  p.finditer(theNukeScriptText)
the3Lines = p.findall(theNukeScriptText)

the3LinesString = ''.join(the3Lines)

theOldSeq = the3LinesString.split('\n')[0]
print str(the3LinesString.split('\n')[0])
theNewSeq = 'file /Volumes/raid0/Z353_002_comp_v27.%04d.cin'


theFile = open('/Volumes/raid0/Z353_001_comp_v05.nk', "w")
theFile.write(theNukeScriptText.replace(theOldSeq,theNewSeq))
theFile.close()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090713/447ac126/attachment.htm>


More information about the Tutor mailing list