I am trying to get a script working, where it will check the existance of an IP in a lookup csv file, and then if it exists take the third element and remove that third element from another (second) file. Here is a extract of what I have:
for line in fileinput.input(hostsURLFileLoc,inplace =1):
elements = open(hostsLookFileLoc, 'r').read().split(".").split("\n")
first = elements[0].strip()
third = elements[2].strip()
if first == hostIP:
if line != third:
print line.strip()
This obviously doesn’t work, I have tried playing with a few options, but here is my latest (crazy) attempt.
I think the problem is that there are two input files open at once.
Any thoughts welcome,
Cheers
All right, even though I haven’t got any response to my comment on the question, here’s my shot at a general answer. If I’ve got something wrong, just say so and I’ll edit to try to address the errors.
First, here are my assumptions. You have two files, who’s names are stored in the
HostsLookFileLocandHostsURLFileLocvariables.The file at
HostsLookFileLocis a CSV file, with an IP address in the third column of each row. Something like this:HostsLookFile.csv:
The file at
HostsURLFileLocis a flat text file with one IP address per line, like so:HostsURLFile.txt:
Your goal is to read and then rewrite the
HostsURLFile.txtfile, excluding all of the IP addresses that are found in the third column of a row in the CSV file. In the example lists above, localhost (127.0.0.1) and python.org (82.94.164.162) would be excluded, but the rest of the IPs in the list would remain.Here’s how I’d do it, in three steps:
csvmodule to find the IP addresses. Stick them into aset.list, closing the file afterwards.Code:
This code is deliberately simple. There are a few things that could be improved, if they are important to your use case: