Home > Software design >  Parse txt file and save in python variable
Parse txt file and save in python variable

Time:03-09

I have a txt file containing following lines

term accept_1  
protocol:: tcp 
destination-port:: 24  


term accept_2  
protocol:: tcp 
source-port:: 21  
source-port-port:: 22  

What I am trying to do is the following: for each term, save the protocol in one variable, and the ports too (probably in an array).

I end up my research with PLY (Python Lex-Yacc), but I found it overcomplicated for my needs.

My actual code:

with fileinput.FileInput(file_pol,inplace = True, backup ='.bak') as policy:
        for line in policy:
            if "destination-port::" in line:
                extract_port = re.findall("\d ",line)
            elif  "source-port::" in line:
                extract_port = re.findall("\d ",line) 

The above is basically working but I miss the relation between term, protocol, port.

CodePudding user response:

Use a dictionary of dictionaries.

from collections import defaultdict

policy_dict = defaultdict(dict)

for line in policy:
    key, value = line.strip().split()
    if key == 'term':
        term = value
    elif key.endswith('::')
        policy_dict[term][key[:-2]] = value
  • Related