Python monitoring file content changes

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.