ADE
ADE

Reputation: 423

Check if a line exists in a file

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()

Upvotes: 9

Views: 58440

Answers (7)

jfs
jfs

Reputation: 414245

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.

Upvotes: 9

DondoJJJ
DondoJJJ

Reputation: 1

might be something like this

line="the line you are searching for"

logfile = open('ip.log', 'r')
loglist = logfile.readlines()
logfile.close()

if line not in loglist:
    loglist.append(line)

new_logfile = open("pathToTheFile/logfile", 'w')
for lines in loglist:
    new_logfile.write(lines)

Upvotes: 0

Chris Morgan
Chris Morgan

Reputation: 90752

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')

Upvotes: 7

Andrej
Andrej

Reputation: 391

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.

Upvotes: 12

Zack Bloom
Zack Bloom

Reputation: 8417

Iterating over the lines allows you to stop loading the file when you find a match, and prevents you from having to hold the entire file in memory.

def log_host(self):
    host = str(self.CLIENT_HOST)

    with open('ip.log', 'r+') as logfile:
        for line in logfile:
            if line.strip() == host:
                return

        # Move to the end of the file:
        logfile.seek(0, 2)
        logfile.write(host + "\n")

Upvotes: 0

sramij
sramij

Reputation: 4925

Use python filter:

file = open('ip.log', 'r')
flines = file.readlines()
res = filter(lambda x: self.CLIENT_HOST in x, flines)
if len(res) == 0:
  file.write(str(self.CLIENT_HOST)+"\n")
  file.close()

Upvotes: 2

Sunjay Varma
Sunjay Varma

Reputation: 5115

Change open('ip.log', 'a+') to open('ip.log', 'r'), then write the file again later or write to a new file. Otherwise you are just making the file infinitely longer.

Upvotes: 0

Related Questions