匹配后,使用 python 获取文件中的下一行

after match, get next line in a file using python

我有一个包含多行的文件,如下所示:

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

我想获取下一行,如果在上一行中找到匹配项,我将如何做。

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)

查看这个关于在循环中获取下一个值(在你的例子中是下一行)的问题。

Python - Previous and next values inside a loop

迭代文本中的每一行,然后在找到匹配项时使用next

例如:

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)