I'm trying to replace alls multiples lines in a text file who are beginning by: setAttr ".os" and ending by: setAttr ".sf".
As lines between begin and ending are unknown and variable...
The issue is that it only replace one occurrence, if variable old
find differents results.
firstFrame = str(80)
lastFrame = str(200)
begin = 'setAttr ".os" '
ending = 'setAttr ".sf" '
new = """setAttr ".os" """ firstFrame """;
setAttr ".oe" """ lastFrame """;
setAttr ".ss" """ firstFrame """;
setAttr ".se" """ lastFrame """;
"""
with open('pathToFile.txt', 'r') as read_stream:
file1 = read_stream.read()
f1_start = file1.index(begin)
f1_end = file1.index(ending, f1_start)
old = file1[f1_start:(f1_end 18)]
file1 = file1.replace(old, new )
with open('pathToFile.txt', 'w') as read_stream:
read_stream.write(file1)
I think my error is at line:
old = file1[f1_start:(f1_end 18)]
But I doesn't know how to make this line variable,
CodePudding user response:
You can't write lines to your original file while you are reading it. I am using a separate name here. You'll have to rename/remove at the end.
I would just do it line by line.
firstFrame = '80'
lastFrame = '200'
begin = 'setAttr ".os" '
ending = 'setAttr ".sf" '
new = f"""\
setAttr ".os" {firstFrame};
setAttr ".oe" {lastFrame};
setAttr ".ss" {firstFrame};
setAttr ".se" {lastFrame};"""
fout = open('pathToNewFile.txt','w')
looking = begin
skipping = False
for line in open('pathToFile.txt'):
if line.startswith(begin):
skipping = True
fout.write(new)
elif line.startswith(ending):
skipping = False
elif not skipping:
fout.write(line)