您需要使用标志来切换何时进行替换;当你看到这.method
条线时设置它,当你看到它时再次重置它.end method
。
然后,您仅在上下文标志为 True 时查找要修复的行:
with open('textfile.text', 'r+') as tfile:
incontext = False
pos = 0
for line in tfile:
pos += len(line) # The read-ahead buffer means we can't use relative seeks.
# Toggle context
if line.strip().startswith('.method'):
incontext = True
continue
if line.strip().startswith('.end method'):
incontext = False
continue
if incontext and 'const/4 v0, 0x1' in line:
line = line.replace('0x1', '0x0')
tfile.seek(pos - len(line))
tfile.write(line)
请注意,以上内容会就地覆盖文件;这仅在您的替换与替换文本的长度完全相同时才有效。
如果要更改行的长度(更短,更长),则需要将其写入新文件(或sys.stdout
):
with open('textfile.text', 'r') as tfile:
with open('outputfile.text', 'w') as output:
incontext = False
for line in tfile:
# Toggle context
if line.strip().startswith('.method'):
incontext = True
if line.strip().startswith('.end method'):
incontext = False
if incontext and 'const/4 v0, 0x1' in line:
line = line.replace('0x1', '0x0')
# Write every line to the output file
output.write(line)