首页 > 解决方案 > 在python中拖尾文件

问题描述

如何从 python 中“关注”类似于 tail 命令的文件?例如,我认为以下内容会起作用:

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

但是,当这些行被添加并保存到相关文件中时,它似乎并没有出现在“新行”上。在python中尾随文件的正确方法是什么?

标签: pythoncoroutine

解决方案


你可以使用这样的东西:

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

推荐阅读