使用Python监控文件内容变化代码实例
2018-06-04 08:52
1616 查看
利用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】监控文件内容增删改操作变化
- Java使用WatchService监控文件内容变化的示例
- 使用Python对Csv文件操作实例代码
- Python复制Word内容并使用格式设字体与大小实例代码
- python使用正则搜索字符串或文件中的浮点数代码实例
- python3.4学习笔记(十三) 网络爬虫实例代码,使用pyspider抓取多牛投资吧里面的文章信息,抓取政府网新闻内容
- Python中使用Inotify监控文件实例
- python使用正则搜索字符串或文件中的浮点数代码实例
- Python中使用Inotify监控文件实例
- Python之文件目录遍历实例代码
- 使用VBS访问外部文本文件一些方法和脚本实例代码
- Python实现多线程下载文件的代码实例
- python 监控文件变化
- Python实现多线程下载文件的代码实例
- linux下使用inotify监控文件变化
- 使用python 更改文件内容
- 用两种不同的方法导出ORACLE 查询数据为CSV 文件 (python 代码 与 使用 utl_file 包)
- python2.7删除文件夹和删除文件代码实例
- 《java核心技术》第八版14.6节使用阻塞队列的代码(生产者—消费者,根据关键字搜索文件内容)
- 工具类commons-io的Tailer用法,用来监控文件内容的变化情况