如何解决Python,在文本文件中查找行,然后跳转到下一个'string-to-find'
要搜索的字符串:
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#'}}....
我想遍历获取的文本文件并将文本文件中的“百分比”值替换为“新”值。 我到目前为止:
- 按行打开文件,在字典中找到关键字并打印下一行。
我找不到的:
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)
但这似乎弄乱了迭代器。
解决方法
我会这样做(只要您的正则表达式是字符串):
with open("./playbooks/qos/policy_map_PM_QOS_C_V-50-50-0-0.cfg","r") as file:
line = True
while line:
line = file.readline()
for key in qos.keys():
if key in line:
print(line)
line1=file.readline()
line2=file.readline()
print(line1)
print(line2)
break # otherwise it'll continue checking the other keys after one is found,if you want that functionality then remove this break
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。