嗨,我正在读一个文件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()发布于 2016-04-20 00:52:40
您可以通过一些正则表达式来提取所需的内容。
尝试下面的代码片段:
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发布于 2016-04-20 00:57:15
试试这个:
with open('tesxt.txt') as f:
for line in f:
if all(i not in line for i in ['Number', 'Last']) and line !='\n':
print(line.strip().split()[:3])它应该可以工作,因为您知道Number和Last不在您需要打印的行中。没有必要写正则表达式
https://stackoverflow.com/questions/36731724
复制相似问题