The Python Oracle

Get only new lines from file

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Quiet Intelligence

--

Chapters
00:00 Question
00:58 Accepted answer (Score 5)
01:46 Answer 2 (Score 2)
01:57 Answer 3 (Score 0)
02:10 Thank you

--

Full question
https://stackoverflow.com/questions/2481...

Accepted answer links:
[Detect File Change Without Polling]: https://stackoverflow.com/questions/5738...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #logging #python3x

#avk47



ACCEPTED ANSWER

Score 5


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




ANSWER 2

Score 2


with open('/var/log/logfile.log','r') as f:
    for line in f:
        print line



ANSWER 3

Score 0


Try This,

readfile = open('/var/log/logfile.log','r')
if readfile:
   for lines in readfile:
      print lines
readfile.close()