Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only new lines from file

Currently i have this piece of code, but it reads all lines, and then watch the file with the while True statement:

with open('/var/log/logfile.log') as f:
        while True:
            line = f.readline()
            if not line:
                time.sleep(1)
            else:
                print(line)

I actually only need new lines coming after the lines already detected when opening the file - anybody who can help me out? Maybe a better way to watch it aswell, than with the while statement?

Another problem is that on Linux machines the script is actually locking the file so it can not be written to, before i close the script again. On OS X it works fine. Could also be nice with an idea to work around this.

Hope there is somebody out there who have been working with something similar.

like image 234
Adionditsak Avatar asked Jul 18 '14 06:07

Adionditsak


People also ask

Does readline read newline?

The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end. This method returns the empty string when it reaches the end of the file.

How do I read 10 lines from a file in Python?

Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously.

How do I make a file few lines read only in Python?

Use readlines() to Read the range of line from the File You can use an index number as a line number to extract a set of lines from it. This is the most straightforward way to read a specific line from a file in Python.


1 Answers

You could initially read the file completely, then close it, and keep a change monitor over it, this monitor is implemented below using polling.

import time

filePath = '/var/log/logfile.log'

lastLine = None
with open(filePath,'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
            print(line)
            lastLine = line

while True:
    with open(filePath,'r') as f:
        lines = f.readlines()
    if lines[-1] != lastLine:
        lastLine = lines[-1]
        print(lines[-1])
    time.sleep(1)

But you could also use tools like those described at: Detect File Change Without Polling

like image 83
Pablo Francisco Pérez Hidalgo Avatar answered Sep 21 '22 04:09

Pablo Francisco Pérez Hidalgo