Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a line exists in a file

Tags:

python

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()
like image 885
ADE Avatar asked Oct 15 '11 01:10

ADE


3 Answers

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.

like image 131
jfs Avatar answered Sep 21 '22 13:09

jfs


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.

like image 23
Andrej Avatar answered Sep 21 '22 13:09

Andrej


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')
like image 32
Chris Morgan Avatar answered Sep 21 '22 13:09

Chris Morgan