【问题标题】:Tailing a file in python在python中拖尾文件
【发布时间】:2020-06-21 21:03:59
【问题描述】:

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

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

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

【问题讨论】:

标签: python coroutine


【解决方案1】:

你可以这样使用:

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

【讨论】:

    【解决方案2】:

    我能想到的最好的:

    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
    

    我建议在“with”语句中打开文件,以便正确关闭文件(如果不这样做,按 ctrl+C 可能会使文件保持打开状态)。
    并且您需要在每个 readlines 之后使用“seek”回到起点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 2021-02-08
      • 2015-05-29
      • 2017-11-08
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      相关资源
      最近更新 更多