check if a line exists in a file python
logfile = open('ip.log', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
if str(self.CLIENT_HOST) in line:
print "Found it"
found = True
if not found:
logfile = open('ip.log', 'a')
logfile.write(str(self.CLIENT_HOST)+"\n")
logfile.close()
This is my first quick solution. Very unclean and not yet sophisticated, but should work.
I think this should work, and it's neater and more robust than any of the other answers yet. If it doesn't, then you may need to open another file for writing (first file 'r'
, second file 'a'
). Also I've gone for using x.rstrip('\r\n')
and ==
rather than in
to make sure it's correct. I don't know what your CLIENT_HOST
variable is. If your CLIENT_HOST
is already a str, throw away the first line and change the others back to referencing it directly.
value = str(self.CLIENT_HOST)
with open('ip.log', 'a+') as f:
if not any(value == x.rstrip('\r\n') for x in f):
f.write(value + '\n')
To append to the log file a client host string if it is not already present you could:
with open('ip.log', 'r+') as f:
for line in f:
if self.CLIENT_HOST in line:
break
else: # not found
print >>f, self.CLIENT_HOST
Note: the indentation of the else
statement is not an error. It is a Python feature to allow for
and while
loops to have an else
clause. It is run if break
statement is not executed inside the loop.