This article mainly introduces the use of Python monitoring file content change code, has a certain reference value, now share to everyone, the need for friends can refer to
File monitoring in Python there are two main libraries, one is pyinotify and the other is watchdog. Pyinotify relies on the Linux platform INotify, today we will discuss the next pyinotify.
Use seek to monitor file content and print out changes:
#/usr/bin/env python#-*-coding=utf-8-*-pos = 0while True: con = open ("A.txt") if pos! = 0: con.seek (pos,0) C3/>while True: Line = Con.readline () if Line.strip (): print Line.strip () pos = pos + len (line) if Not Line.strip (): break Con.close ()
Use the tool pyinotify Monitor file content changes, when the file becomes larger, you can easily complete the task:
#!/usr/bin/env python#-*-coding=utf-8-*-import osimport datetimeimport pyinotifyimport Logging pos = 0def printlog ():
global Pos Try: fd = open ("Log/a.txt") if pos! = 0: fd.seek (pos,0) while True: line = Fd.readline () if Line.strip (): print Line.strip () pos = pos + len (line) if not Line.strip (): Break fd.close () except exception,e: print str (e) class MyEventHandler (pyinotify. processevent): def process_in_modify (self,event): try: printlog () except exception,e: Print Str (e) def main (): printlog () wm = Pyinotify. Watchmanager () wm.add_watch ("Log/a.txt", pyinotify. all_events,rec=true) eh = MyEventHandler () notifier = pyinotify. Notifier (Wm,eh) notifier.loop () if __name__ = = "__main__": Main ()
Related recommendations:
How to use Python's requests package to implement a mock login