简体   繁体   中英

check if a line exists in a file python

How can I check if a line exists in a file and write the line to the file if it does not exist using Python

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

cheers

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.

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.

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

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

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM