AlliDeacon
AlliDeacon

Reputation: 1495

Looping/reading through text file not working as expected -- python 2.7

I am working on a program that will ping a list of servers, and will send a notice with a list of any that fail. However, I'm stuck creating the list. This is my code below to read a text file, pull out the IP and the Servers name. My ping function loops through this list. Currently my print line shows the last IP in the list, and the ip_list only contains the first IP in the list. I'm not sure what I'm doing wrong.

ip_list = list()

with open('servers.txt', 'rb') as infile :
        for line in infile:
            print line
            full_line = line.rstrip()
            info = full_line.split()
            IP = info[0]
            server = info[3]
            ip_list.append((IP, server))

print ip_list

I'm not sure how to show the input. It is a text file with 30 lines that are formatted as below:

10.14.12.61 Pointer (PTR) server1.xxxxx.com. ?1/?15/?2016 2:00:00 AM

The print line statements gives me (the last line in the file):

192.168.1.90 Pointer (PTR) server30.gb.xxxx.com. static

The print ip_list gives me this (the first line in the file):

[('10.14.12.61', 'server1.xxxx.com.')]

My expected result for ip_list is a list of the 30 lines, pulling out the IP and Server name. It looks like it's pulling the right information from the line of text, but only for the 1st line. The program is reading through to the last line, though.

so ip_list would be

('10.14.12.61', 'server1.xxxxx.com')
('192.168.1.212', 'server2.xxxxx.com')
('192.168.1.229', 'server3.xxxxx.com')
('192.168.1.90', 'server30.xxxxx.com')

Upvotes: 1

Views: 147

Answers (1)

AlliDeacon
AlliDeacon

Reputation: 1495

The file was lacking the newline character.

Corrected the file and the code works.

Upvotes: 1

Related Questions