1

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)
user3682875
  • 49
  • 1
  • 1
  • 5

2 Answers2

1

Check out this question about getting the next value(in your case the next line) in a loop.

Python - Previous and next values inside a loop

Jacob N
  • 76
  • 7
1

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)
Rakesh
  • 81,458
  • 17
  • 76
  • 113