Search code examples
pythonreadline

read specific line range from file


imho a pretty simple problem, but i cant find a solution.

i first get all files from a directory and read them in. after that i have a regex if statement. if we have a match, i need the line number cause thats where a new config part starts. after getting all line numbers i want to read the lines from match1 to match2. next from match3 to match4 and from match 4 to the end of the file.

file:

PROMOPT# show startup-config
!
hostname bla
!
no banner motd

PROMPT# show system

sysinfo(System Information)
Main Memory Size : 512 MB
flash Memory Size : 256 MB
H/W Revision : VA0
NOS Version : 1.15

PROMPT# show version

NOS version 1.15_0006

Code:

for file in files:
        with open (file, 'r') as file:
            for num, line in enumerate(file, 1):
                line = line.strip()
                if re.findall(r'(PROMTP#)', line):
                    configpart = line.split()
                    configpart = configpart[2]

                    print('name: ', configpart, 'linenumber: ', num)

Output:

name: startup-config linenumber: 1
name: system linenumber: 58
name: version linenumber: 70
name: startup-config linenumber: 1
name: system linenumber: 58
name: version linenumber: 70

so now i want to

file.readlines()[1:57]
file.readlines()[58:69]
file.readlines()[70:to end of file]

but i cant figure out a loop doing this for me.


Solution

  • You should read all of the lines into a variable, then perform your operations on this variable.

    I am not sure about your desired output exactly, but I would probably store them in a dictionary and then extract them using file name.

    import re
    files = ["files/sample.txt"]
    output = {}
    for file in files:
        with open (file, 'r') as f:
            lines = f.readlines()
            output[file] = []
            command = []
            for line in lines:
                if "PROMPT" in line and lines.index(line) != 0:
                    output[file].append(command)
                    command = []
                command.append(line)
            output[file].append(command)
    
    # then to extract
    # first command
    output[your_file_name][0] 
    # second command
    output[your_file_name][1] 
    # another file
    output[your_file_name_1][0] 
    
    # or..
    for command in output[your_file_name:
        do_something_with_command(command)