您好我正在阅读以下格式的文件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()
答案 0 :(得分:1)
您可以借助一点正则表达式提取所需的内容。
请尝试以下代码段:
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
答案 1 :(得分:1)
试试这个:
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
不在您需要打印的行中。没有必要写一个正则表达式