How can I check if a line exists in a file?
I'd also like to write the line to the file if it does not exist.
This is my current attempt:
logfile = open('ip.log', 'a+')
while 1:
line = logfile.readline()
#line.replace("\n", "")
print line
if line == str(self.CLIENT_HOST):
print "Line Found Skipping"
else:
logfile.write(str(self.CLIENT_HOST)+"\n")
if not line:
print "EOF Reached"
break
print line
logfile.close()
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With