需求:
- 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")
标签:文件,Python,内容,跟踪,监控,time,line From: https://www.cnblogs.com/liqi175/p/16960437.html