-1

How can I 'follow' a file similar to the tail command from within python? For example, I though t the following would work:

def tail(filepath):
    source = open(filepath)
    source.seek(0,2)
    while True:
        chunk = source.readline()
        yield chunk
    source.close()

However, it doesn't seem to pick up on 'new lines' after it seems to the end, when those lines are added and saved to the file in question. What would be the correct way to tail a file in python?

David542
  • 104,438
  • 178
  • 489
  • 842
  • Does this answer your question? [Reading from a frequently updated file](https://stackoverflow.com/questions/5419888/reading-from-a-frequently-updated-file) – AMC Mar 10 '20 at 01:06

2 Answers2

0

You could use something like this:

import os
from time import sleep

filename = 'file.test' # filename to 'follow'
with open(filename) as file:
    st_size = os.stat(filename)[6]
    file.seek(st_size) # move to the eof
    while True:
        where = file.tell() # save eof position
        line = file.readline()
        if not line: # if there is no new line
            sleep(1)
            file.seek(where) # move back
        else: # if there is a new line
            print(line.replace('\n','')) # print new line
exiz
  • 93
  • 6
0

The best I could figure out:

with open('e:\\test.txt','r') as f:
    initial_length = len(f.readlines())
    while True:
        f.seek(0)
        lines = f.readlines()
        curr_length = len(lines)
        if curr_length > initial_length:
            for line in lines[initial_length:curr_length]:
                print(line)
            initial_length = curr_length

I would recommend opening the file inside a "with" statement so the file gets closed properly (if you don't, hitting ctrl+C might leave the file open).
And you need to use "seek" to get back to the start after each readlines.

Sam
  • 147
  • 11