There is data:

time timezone 120 time daylight-time-rule Western-Europe ip access-list extended "test" строка строка exit ip access-list extended "test2" строка строка exit ip access-list extended "test3" строка строка exit 

The task is to parse the block starting from "ip access-list extended" test "" to the line exit

I managed with only one condition, that is, parsing from the ip access-list extended "test" and to the end. Tell me how to make the exit condition on the line "Exit"

Code

 with open("File", "r") as file: for line in file: if 'ip access-list extended "from_wifi"' in line: print(file.read()) 

    2 answers 2

    file is an iterator over lines in Python. The peculiarity of iterators is that they are spent on reading, so the lines will not be read twice:

     from itertools import takewhile for line in file: if line.startswith("ip access-list extended"): access_list = ''.join(takewhile(lambda line: line.strip() != "exit", file)) 

    This code reads the file line by line until it encounters a block with an access-list. Then all lines — until a line equal to exit meets — are considered to belong to the current access-list block. After this, the loop continues and the remaining blocks are read to the end of the file.

    If the file is small, then using the regular expression all access-list blocks can be immediately obtained:

     import re text = file.read() access_lists = re.findall(r"ip access-list extended\s+(.*?)\s+^\s*exit\s*$", text, flags=re.DOTALL | re.MULTILINE) 

    Result for input in question:

     ['"test" \n строка\n строка', '"test2" \n строка\n строка', '"test3" \n строка\n строка'] 

      Here two options are possible:

      1. Use the readline or readlines methods to read the file line by line, or
      2. We load the entire file into a string and look for the indices of the beginning and end of the part we need using the find or index methods. Next, we get the desired part of the cut and work with it.