用未知的内部替换多个不同的字符串?
Replace multiple different strings with unknown inside?
我正在尝试替换文本文件中以以下内容开头的所有多行:setAttr ".os"
并以:setAttr ".sf".
结尾
由于开始和结束之间的界线未知且可变...
问题是如果变量 old
找到不同的结果,它只会替换一次。
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)
我认为我的错误在行:
old = file1[f1_start:(f1_end+18)]
但是我不知道如何使这一行变量,
您不能在阅读原始文件时向其写入行。我在这里使用一个单独的名称。最后你必须rename/remove。
我会一行一行地做。
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)
我正在尝试替换文本文件中以以下内容开头的所有多行:setAttr ".os" 并以:setAttr ".sf".
结尾由于开始和结束之间的界线未知且可变...
问题是如果变量 old
找到不同的结果,它只会替换一次。
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)
我认为我的错误在行:
old = file1[f1_start:(f1_end+18)]
但是我不知道如何使这一行变量,
您不能在阅读原始文件时向其写入行。我在这里使用一个单独的名称。最后你必须rename/remove。
我会一行一行地做。
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)