Python读取文件并打印
您好,我正在读取以下格式的data.txt文件Python读取文件并打印,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,您好,我正在读取以下格式的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 Neig
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’)
您可以借助少量正则表达式提取所需的内容 请尝试以下代码段:
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
试试这个:
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
不在需要打印的行中。没有必要编写正则表达式为什么要做zip
的事情?你不需要转置。很好用,谢谢。在上面的例子中,我提到它从第7行开始,我们可以修改它,使它从端口邻居设备ID邻居端口ID TTL旁边的行开始。我们能那样做吗?都是你的了。做你想做的事。事实上,我鼓励您使用代码。这是最好的学习方式。嗨,萨利姆,我正在尝试另一种模式。
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])