我想在“配置vdom”字符串的第三次匹配之后追加行。不幸的是,脚本只考虑第一场比赛。
原始代码:
x = list()
def z():
with open('test.conf', 'r') as rf:
for line in rf:
if 'config vdom\n' in line:
while True:
line = (rf.__next__())
if 'end\n' in line:
break
x.append(line)
with open('test.txt', 'w') as wf:
wf.writelines(x)
return我计划使用枚举,但不确定如何在添加下一行时应用它。
枚举行:
z = [i for i, n in enumerate(y) if n == 'config vdom\n'][2]
print('Line', z, ':', y[z])输出:
Line 10310 : config vdom样本数据:
config vdom
config system global
set admin-maintainer disable
set admin-scp enable
end
config vdom*
config system accprofile
edit "prof_admin"
set admingrp read-write
set utmgrp read-write
set vpngrp read-write
set wanoptgrp read-write
set wifi read-write
config vdom*
test sample data
end预期输出:它应该是下面的三行将添加到x列表中。
config vdom*
test sample data
end发布于 2018-04-24 06:45:41
这会有帮助的。
with open('test.txt', 'a') as wf:
with open('test.conf', 'r') as rf:
c = 0 #Checkvalue
for line in rf:
if 'config vdom\n' in line:
c += 1
if c == 3: #Check if 3rd "config vdom"
while True:
line = next(rf)
if 'end\n' in line:
break
wf.writelines(line) #Write required content. 发布于 2018-04-24 06:47:55
itertools.groupby可以帮助:
from itertools import groupby
from io import StringIO
text = '''config vdom
config system global
set admin-maintainer disable
set admin-scp enable
end
config vdom*
config system accprofile
edit "prof_admin"
set admingrp read-write
set utmgrp read-write
set vpngrp read-write
set wanoptgrp read-write
set wifi read-write
config vdom*
test sample data
end'''
count = 0
with StringIO(text) as file:
for key, group in groupby(file, key=lambda x: 'config vdom' in x):
if key is True:
count += 1
if count == 3 and key is False:
with StringIO() as out_file:
out_file.writelines(group)
print(out_file.getvalue())此打印(或写入您的文件)
test sample data
end...is是您想要的输出吗?
key对于出现'config vdom'的每一行都是True,对于所有其他行都是false。group收集所有行,直到key的值发生变化。
您需要用所需的文件替换所有StringIO部件。
https://stackoverflow.com/questions/49994703
复制相似问题