Question : Reading / Parsing IP and Port from file

I'm trying to read and parse the ip and port from a file. I'm pretty close to getting it, but
somethings not right.

The file is data.txt has the contents
IP_ADDRESS=127.0.0.1
PORT=3031

The result after running the program is backwards
PORT:  127.0.0.1

IP:  3031

Why I don't understand and what to do to make PORT: 3031 and IP: 127.0.0.1
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
myFile = open("data.txt","r")
for line in myFile.readlines():
	if line.find("PORT"):
		ip = line.split("=")[1]
		print "PORT:  " + str(ip)
	elif line.find("IP_ADDRESS"):
		port = line.split("=")[1]
		print "IP:  " + str(port)
Open in New Window Select All

Answer : Reading / Parsing IP and Port from file

The "find" method returns -1 if it doesn't find anything, and "if -1" succeeds - that is, -1 is considered to be True.

What you'd better off doing is saying 'if "PORT" in line:" - it's easier to read and it does exactly what you want.

Your "port" and "ip" variables are the wrong way round - you're parsing the port into a variable called "ip" and vice versa.  It's not the cause of any breakage, but it could be the cause of confusion!

An aside: your output is double-spaced because the lines you're iterating through contain the newlines from data.txt, but your "print" statements are adding newlines as well.  Using line.strip() prevents that.

Here's the working code:
1:
2:
3:
4:
5:
6:
7:
8:
9:
myFile = open("data.txt","r")
for line in myFile.readlines():
        line = line.strip()
        if "PORT" in line:
                port = line.split("=")[1]
                print "PORT:  " + str(port)
        elif "IP_ADDRESS" in line:
                ip = line.split("=")[1]
                print "IP:  " + str(ip)
Open in New Window Select All
Random Solutions  
 
programming4us programming4us