Use Python to monitor file content change codes

Source: Internet
Author: User
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

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.