使用Python监控文件内容变化代码实例

yipeiwu_com5年前Python基础

利用seek监控文件内容,并打印出变化内容:

#/usr/bin/env python
#-*- coding=utf-8 -*-
 
pos = 0
while 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():
    break
  con.close()

利用工具pyinotify监控文件内容变化,当文件逐渐变大时,可轻松完成任务:

#!/usr/bin/env python
#-*- coding=utf-8 -*-
import os
import datetime
import pyinotify
import logging
 
pos = 0
def 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()

相关文章

Python遍历pandas数据方法总结

Python遍历pandas数据方法总结

前言 Pandas是python的一个数据分析包,提供了大量的快速便捷处理数据的函数和方法。其中Pandas定义了Series 和 DataFrame两种数据类型,这使数据操作变得更简...

Python使用xlrd模块操作Excel数据导入的方法

本文实例讲述了Python使用xlrd模块操作Excel数据导入的方法。分享给大家供大家参考。具体分析如下: xlrd是一个基于python的可以读取excel文件的产品。和pyExce...

Python算法应用实战之队列详解

Python算法应用实战之队列详解

队列(queue) 队列是先进先出(FIFO, First-In-First-Out)的线性表,在具体应用中通常用链表或者数组来实现,队列只允许在后端(称为rear)进行插入操作,在前端...

对python pandas读取剪贴板内容的方法详解

我使用的Python3.5,32版本win764位系统,pandas0.19版本,使用df=pd.read_clipboard()的时候读不到数据,百度查找解决方法,找到了一个比较靠谱的...

python的turtle库使用详解

python的turtle库使用详解

python中的turtle库是3.6版本中新推出的绘图工具库,那么如何使用呢?下面小编给大家分享一下。 首先打开pycharm软件,右键单击选择新建一个python file 接下来...