嗨,我正在读取以下格式的data.txt文件。
Last table change time : 6:55:12 ago
Number of table inserts : 3
Number of table deletes : 0
Number of table drops : 0
Number of table age-outs : 0
Port Neighbor Device ID Neighbor Port ID TTL
Et1 Arista2 Ethernet1 120
Et2 Arista2 Ethernet2 120
Ma1 Arista2 Management1 120
我需要提取数据并将其打印为
Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1
我正在使用以下代码,但是我只能打印
(“ Et1”,“ Et2”,“ Ma1”)
with open('data.txt') as f:
for x in xrange(6):
next(f)
for line in f:
print zip(*[line.split() for line in f])[0]
f.close()
最佳答案
您可以借助一点正则表达式来提取所需的内容。
尝试以下代码段:
import re
with open('input.txt','r') as fp:
for x in xrange(7):
next(fp)
rx = "\w+"
for line in fp:
data = re.findall(u"\w+", line, re.DOTALL)
if data:
print(', '.join(data[0:-1]))
根据文件内容和格式,它将打印
Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1