Python, find line in text file, and jump to next 'string-to-find'

604 views Asked by At

string to search:

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#'}}....

I would like to iterate through the fetched text file and replace the 'percent' value in the text file with the 'new' value. I did so far:

  • open the file as line per line, find the key in the dictionary and print next line.

What i can't find:

  • open the file, iterate through the file until first key, jump to first percent and then replace bandwidth remaining value.

Code I use so far:[string above is contents of file, 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)

But that seems to mess up the iterator.

1

There are 1 answers

0
EvgenyKolyakov On

I'd have done it this way (as long your regexes are strings):

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