I have a file of IP addresses called “IPs”. When I parse a new IP from my logs, I’d like to see if the new IP is already in file IPs, before I add it. I know how to add the new IP to the file, but I’m having trouble seeing if the new IP is already in the file.
!/usr/bin/python
from IPy import IP
IP = IP('192.168.1.2')
#f=open(IP('IPs', 'r')) #This line doesn't work
f=open('IPs', 'r') # this one doesn't work
for line in f:
if IP == line:
print "Found " +IP +" before"
f.close()
In the file “IPs”, each IP address is on it’s own line. As such:
222.111.222.111
222.111.222.112
Also tried to put the file IPs in to an array, but not having good luck with that either.
Any ideas?
Thank you,
Gary
Now you have your IPs in a list (iplist) and you can easily add your newip to it
iplist.append(newip)or do anything else you please.Edit:
Some excellent books for learning Python:
If you’re worried about programming being difficult, there’s a book that’s geared towards kids, but I honestly found it both easy-to-digest and informative.
Snake Wrangling for Kids
Another great resource for learning Python is How to Think Like a Computer Scientist.
There’s also the tutorial on the official Python website. It’s a little dry compared to the previous ones.
Alan Gauld, one of the foremost contributors to the tutor@python.org mailing list has this tutorial that’s really good and also is adapted to Python 3. He also includes some other languages for comparison.
If you want a good dead-tree book, I’ve heard that Core Python Programming by Wesley Chun is a really good resource. He also contributes to the python tutor list every so often.
The tutor list is another good place to learn about python – reading, replying, and asking your own questions. I actually learned most of my python by trying to answer as many of the questions I could. I’d seriously recommend subscribing to the tutor list if you want to learn Python.