The Python Oracle

Get only new lines from file

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island Looping

--

Chapters
00:00 Get Only New Lines From File
00:46 Answer 1 Score 0
00:54 Accepted Answer Score 5
01:24 Answer 3 Score 2
01:29 Thank you

--

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

--

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