Search code examples
python-3.6startswith

after match, get next line in a file using python


i have a file with multiple lines like this:

Port id: 20
Port Discription: 20
System Name: cisco-sw-1st
System Description:
Cisco 3750cx Switch

i want to get the next line, if the match found in the previous line, how would i do that.

with open("system_detail.txt") as fh:
show_lldp = fh.readlines()

data_lldp = {}

for line in show_lldp:
    if line.startswith("System Name: "):
        fields = line.strip().split(": ")
        data_lldp[fields[0]] = fields[1]
    elif line.startswith("Port id: "):
        fields = line.strip().split(": ")
        data_lldp[fields[0]] = fields[1]
    elif line.startswith("System Description:\n"):
        # here i Want to get the next line and append it to the dictionary as a value and assign a 
        # key to it 
        pass

print()
print(data_lldp)

Solution

  • Iterate each line in text and then use next when match found

    Ex:

    data_lldp = {}
    with open("system_detail.txt") as fh:
        for line in fh:                              #Iterate each line
            if line.startswith("System Name: "):
                fields = line.strip().split(": ")
                data_lldp[fields[0]] = fields[1]
            elif line.startswith("Port id: "):
                fields = line.strip().split(": ")
                data_lldp[fields[0]] = fields[1]
            elif line.startswith("System Description:\n"):
                data_lldp['Description'] = next(fh)        #Use next() to get next line
    
    print()
    print(data_lldp)