gpt4 book ai didi

python - 从文本文件打印多行

转载 作者:行者123 更新时间:2023-12-04 00:44:51 27 4
gpt4 key购买 nike

如果我有这样一个文本文件:

FastEthernet3/1
ip address 0.0.0.0
enable portfast

FastEthernet3/2
ip address 0.0.0.0
enable portfast

FastEthernet3/3
ip address 0.0.0.0

FastEthernet3/4
ip address 0.0.0.0

我想打印出没有启用 portfast 的接口(interface)。我如何在 python 中打印这个?

我有以下代码:

import os
import sys

root = "path to text file like the example above"

os.chdir(root)

current2 = os.getcwd()

print ("CWD = ", current2,"\n")


file = sys.argv[1]

f = open(file)
contents = f.read()
f.close()
print ("Number of GigabitEthernet:",contents.count("interface GigabitEthernet"))
print ("Number of FastEthernet:",contents.count("FastEthernet"))


x = open(file)
string1 = "enable portfast"
for line in x.readlines():
if line.startswith(string1)
print (line)
filehandle.close()

所以我可以找到启用 portfast 的行并打印它,但我希望它打印更多行所以我知道女巫界面启用了 portfast。

最佳答案

基于空行分隔的接口(interface)拆分:

import re
pinterfaces = re.compile("\r?\n\r?\n").split(contents)
# pinterfaces = ['FastEthernet3/1...', 'FastEthernet3/2...', ...]
for pinterface in pinterfaces:
if "enable portfast" in pinterface:
print pinterface

FastEthernet3/1
ip address 0.0.0.0
enable portfast
FastEthernet3/2
ip address 0.0.0.0
enable portfast

关于python - 从文本文件打印多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12511411/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com