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) While true:line = Con.readline () if Line.strip (): Print Line.strip () pos = pos + len (line) if not Line.strip (): Brea K 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 loggingpos = 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 (): Breakfd.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 ()
Python monitoring file content changes