Python - 打印配置行的特定部分

Python - Printing A Specific Part Of A Config Line

我在从我使用的交换机的配置文件中复制信息时遇到问题。当我 运行 下面的脚本时,它会给我一整行,例如 'Switchport Access Vlan 99' 。问题是我只是want/need它到return'Vlan 99'。有什么建议吗?

input_file = open('X:\abc\def\ghi.txt', 'r')
output_file = open('X:\abc\def\jkl.txt', 'w')
for line in input_file:
    if "vlan" in line:
        print(line)
        output_file.write(line)

鉴于所有行都以 'Switchport Access' 开头,您可以只使用字符串方法 replace

line = "Switchport Access Vlan 99"
interesting_part = line.replace("Switchport Access ", "")

根据文件的内容,您可能需要做一些不同的事情。

如果每个赞都是 "Some random text Vlan 99" 那么你可以使用:

for line in input_file:
  if "vlan" in line:
    s = line[line.find("Vlan"):]
    print(s)
    output_file.write(s)

line.find("text") return 如果找到则为字符串的索引,否则为 -1。 line[N:] returns 从索引到末尾的子字符串。

对于另一种获取子字符串的方法,您可以查看 line.split(),然后取该列表的最后一个元素来获取您的号码。