要搜索的字符串:
filecontent = policy-map PM_QOS_C_V-50-50-0-0
class CM_QOS_C_VOICE
priority level 1
police cir percent 9
class CM_QOS_C_VIDEO
priority level 2 percent 15
class CM_QOS_C_ROUTING
bandwidth remaining percent 1
police cir percent 6
class CM_QOS_C_NETMGT
bandwidth remaining percent 1
police cir percent 6
set mpls experimental topmost 7
class CM_QOS_C_CALLSIG
bandwidth remaining percent 1
set mpls experimental topmost 7
police cir percent 6
class CM_QOS_C_SRV
bandwidth remaining percent 7
queue-limit 4096 packets
police cir percent 20
class CM_QOS_C_PRIORITY
bandwidth remaining percent 7
queue-limit 64 packets
police cir percent 30
....
qos = {'VOICE': {'remainingbwspeed': 990.0,
'remainingpercent': 22,
'string': '#VOICE#'},
'VIDEO': {'remainingbwspeed': 405.0,
'remainingpercent': 9,
'string': '#VIDEO#'}}....
我想遍历获取的文本文件并将文本文件中的“百分比”值替换为“新”值。到目前为止我做了:
- 逐行打开文件,在字典中找到键并打印下一行。
我找不到什么:
- 打开文件,遍历文件直到第一个键,跳转到第一个百分比,然后替换带宽剩余值。
到目前为止我使用的代码:[上面的字符串是文件的内容,snippit]
with open("./playbooks/qos/policy_map_PM_QOS_C_V-50-50-0-0.cfg", "r") as file:
for i, line in enumerate(file):
for key, value in qos.items():
pattern = re.compile(key)
for match in re.finditer(pattern, line):
print(line)
line1=file.readline()
line2=file.readline()
print(line1)
print(line2)
但这似乎弄乱了迭代器。