繁体   English   中英

Python 读取文件并打印

[英]Python Reading a file and printing

嗨,我正在阅读以下格式的文件 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

尝试这个:

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

它应该可以工作,因为您知道NumberLast不在您需要打印的行中。 无需编写正则表达式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM