I am trying to get last line from a text file, which I used the solution from What is the most efficient way to get first and last line of a text file?
def read_last_line(filename):
with open(filename, "rb") as f:
first = f.readline()
if f.read(1) == '':
return first
f.seek(-2, 2) # Jump to the second last byte.
while f.read(1) != b"\n": # Until EOL is found...
f.seek(-2, 1) # ...jump back the read byte plus one more.
last = f.readline() # Read last line.
return last.decode('ascii')
It managed to get the last line of the text file successfully if the file is modified by another script/program, but when I modify the text file using Notepad++
the exact same modification as another script/program, it will throw the following exception:
in read_last_line
f.seek(-2, 2)
OSError: [Errno 22] Invalid argument
What I am trying to do is, I used watchdog
to check if there's file changes, and on modify I will call read_last_line
on the modified file.
Sample file
11/26/2020 2:05:12 PM Time Updated: +2ms Regular Update
11/26/2020 2:06:13 PM Time Updated: +4ms Regular Update
11/26/2020 2:07:13 PM Time Updated: +1ms Regular Update
How I am calling the function:
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import ntpath
class FileEventHandler(FileSystemEventHandler):
def __init__(self, filetowatch):
self.file = filetowatch
def on_modified(self, event):
modified_file = ntpath.basename(event.src_path)
if modified_file == self.file:
read_last_line(event.src_path)
if __name__ == "__main__":
event_handler = FileEventHandler("sample.txt")
observer = Observer()
observer.schedule(event_handler, path='C:/Program Files (x86)/SomeTime', recursive=False)
observer.start()
May I know if anyone know what is causing the error?
Platform: Windows 10, Python 3.7.4
UPDATE - ANSWER
So the error was because of fread(1) == ''
which was fixed using falsetru's solution.
The reason why it is not performing the way I expected was because text editor deletes the sample file and create a file using the same file name, therefore fread(1)==''
was triggered (which throws) and using script/program to modify the sample file did not throw simply because I did not delete the file.