Search code examples
pythonnetwork-programmingdefaultgateway

Pulling specific words out of a line of a text file in python


I'm a newbie python programmer and I'm doing some playing around with network coding. In order to check to see whether a connection to the default gateway of my router has occurred, I want to pull the gateway from my ipaddr file and turn it to a variable, however I can't get it to pull the column from a specific line, only the first line.

This is my code so far:

with open('ipaddr.txt', "r") as f:
    line=f.readlines()
    columns = [line.rstrip("\t") for line in f]
    print (line[22])
    print (line[18])
    print (line[26])
    f.close()

I want it to pull from column 39 onward on each of the above lines.


Solution

  • You are using rstrip where you should be using split. You are also reading the file twice readlines() and for line in f.

    with open('ipaddr.txt', "r") as f:
        lines=f.readlines()
        table = [line.split("\t") for line in lines]
        print table[22][39:]
        print table[18][39:]
        print table[26][39:]
        f.close()