Python如何动态监控跟踪文件内容?

需求:

  • Python如何动态监控跟踪文件内容?写个小工具模仿linux中的tail 来监控文件更新的内容?

解答:

  • 利用文件的指针f.seek(0,2)
  • import time
    
    with open("a.txt",mode="rb") as f:
        f.seek(0,2)
        while True:
            time.sleep(0.1)
            line = f.readline()
            if line:
                print(line.decode("utf-8"),end="")

     

  • 效果:
  •  

     

附录:

  • 执行一次,增加内容的代码为
  • import time
    
    with open("a.txt", mode="at", encoding="utf-8") as f:
        info = time.strftime("%Y-%m-%d %H:%M:%S")
        f.write(f"{info} 打工中... \n")

     

 

posted @ 2022-12-06 20:27  o蹲蹲o  阅读(97)  评论(0编辑  收藏  举报