我有一个文本文件,我需要替换一行文字
它是一个非常大的文件,因此将整个文件读入内存并不是最好的方法。
这里有大量的代码块只有两个才能得到一个想法。
我需要做的是用'const/4 v0, 0x1'
替换'const/4 v0, 0x0'
但我只需要替换canCancelFocus()Z
方法中的那个
所以我需要搜索'.method public static canCancelFocus()Z'
行
然后使用该方法将'const/4 v0, 0x1'
替换为'const/4 v0, 0x0'
。
Textfile.text包含:
.method public static CancelFocus()Z
.locals 1
const/4 v0, 0x1
return v0
.end method
.method public static FullSize()Z
.locals 1
const/4 v0, 0x1
return v0
.end method
......
答案 0 :(得分:1)
以下是ya的一些代码:
fp = open("Textfile.text", "r+")
inFunc = False
line = fp.readline()
while line is not None:
if inFunc and "const/4 v0, 0x1" in line:
line = line.replace("0x1", "0x0")
fp.seek(-len(line), 1)
fp.write(line)
elif ".method public static canCancelFocus()Z" in line:
inFunc = True
elif ".end method" in line:
inFunc = False
line = fp.readline()
fp.close()
答案 1 :(得分:1)
您需要使用标记来切换何时进行替换;当您看到.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)