Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python读取文件并打印_Python_Python 2.7_Python 3.x - Fatal编程技术网

Python读取文件并打印

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

您好,我正在读取以下格式的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’)


您可以借助少量正则表达式提取所需的内容

请尝试以下代码段:

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])