Python 如何搜索一行,然后替换后面的一行
我有一个文本文件,我需要替换一行文本 它是一个非常大的文件,所以将整个文件读入内存并不是最好的方法。 这里有很多这样的代码块,只有两块代码可以理解。 我需要做的是用Python 如何搜索一行,然后替换后面的一行,python,python-2.7,Python,Python 2.7,我有一个文本文件,我需要替换一行文本 它是一个非常大的文件,所以将整个文件读入内存并不是最好的方法。 这里有很多这样的代码块,只有两块代码可以理解。 我需要做的是用'const/4v0,0x0'替换'const/4v0,0x0' 但是我只需要替换canCancelFocus()Z方法中的一个 所以我需要搜索行”。方法public static cancancancelfocus()Z' 然后在该方法中将'const/4v0,0x1'替换为'const/4v0,0x0' Textfile.text
'const/4v0,0x0'
替换'const/4v0,0x0'
但是我只需要替换canCancelFocus()Z
方法中的一个
所以我需要搜索行”。方法public static cancancancelfocus()Z'
然后在该方法中将'const/4v0,0x1'
替换为'const/4v0,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
......
下面是一些代码:
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()
您需要使用一个标志来切换何时进行替换;当看到
.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
):
对,我经常在两种语言之间跳来跳去,但我忘了和这件事。无论如何,这只是一个例子。我将对其进行编辑,不将整个文件加载到内存中。第一个文件工作正常,但它正在将整个文本文件读取到内存中。文本文件有1500多行,所以我不确定这是否太多而无法读入内存。第二个挂着,什么也不做。此外,这将需要运行很多次,所以我不确定最好的方法是什么。
对于fp中的line
将比while循环更具pythonic。另外,continue将导致循环返回,而不读取新行,否则没有必要。是的,但我不知道您是否可以编辑该行并将其保存回文件中。
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)