Skip to content Skip to sidebar Skip to footer

Call A Sub-function In A Function To Deal With A Same File In Python?

I am still fight with python copy and replace lines, a question Here. Basically, I want to statistics the number of a pattern in a section, and renew it in the line. I think I ha

Solution 1:

You can use tell and seek to move inside a file, so to do what you want to do, you could use something like this, which I hacked together:

import re

# so, we're looking for the object 'HeyThere'
objectname = 'HeyThere'withopen('input.txt', 'r+') as f:
    line = f.readline()
    pos = f.tell()
    found = Falsewhile line:

        # we only want to alter the part with the # right ObjectAlias, so we use the 'found' flagif'ObjectAlias ' + objectname in line:
            found = Trueif'EndObject'in line:
            found = Falseif found and'BeginKeyframe'in line:

            # we found the Keyframe part, so we read all lines # until EndKeyframe and count each line with 'default'
            sub_line = f.readline()
            frames = 0whilenot'EndKeyframe'in sub_line:
                if'default'in sub_line:
                    frames += 1
                sub_line = f.readline()

            # since we want to override the 'BeginKeyframe', we# have to move back in the file to before this line
            f.seek(pos)

            # now we read the rest of the file, but we skip the# old 'BeginKeyframe' line we want to replace
            f.readline()
            rest = f.read()

            # we jump back to the right position again
            f.seek(pos)

            # and we write our new 'BeginKeyframe' line
            f.write(re.sub('\d+', str(frames), line, count=1))

            # and write the rest of the file
            f.write(rest)
            f.truncate()
            # nothing to do here anymore, just quit the loopbreak# before reading a new line, we keep track# of our current position in the file
        pos = f.tell()
        line = f.readline()

The comments pretty much explain what's going on.

Given an input file like

foo
bar
BeginObject
something
something
ObjectAlias NotMe
lines
more lines
BeginKeyframe 2212   
foo
bar default
foo default
bar default
EndKeyframe
EndObject
foo
bar
BeginObject
something
something
ObjectAlias HeyThere
lines
more lines
BeginKeyframe 4324312   
foo
bar default
foo default
bar default
foo default
bar default
foo default
bar
EndKeyframe
EndObject

it will replace the line

BeginKeyframe 43243 12   

with

BeginKeyframe 6 12   

Post a Comment for "Call A Sub-function In A Function To Deal With A Same File In Python?"