简体   繁体   中英

Python Reading a file and printing

Hi I am reading a file data.txt which is in the below format.

    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

I need to extract the data and print it as

Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1

I am using the below code, however I am only able to print

('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()

You can extract desired content with help of little bit regex.

Try following code snippet:

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

Depending on file content and format, it will print

Et1, Arista2, Ethernet1
Et2, Arista2, Ethernet2
Ma1, Arista2, Management1

Try this:

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

it should work since you know Number and Last are not in the lines you need to print. There's no need to write a regex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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