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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With