您好,登錄后才能下訂單哦!
這篇文章主要介紹了使用Python監(jiān)控文件內(nèi)容變化的方法,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
Python是一種編程語(yǔ)言,內(nèi)置了許多有效的工具,Python幾乎無(wú)所不能,該語(yǔ)言通俗易懂、容易入門(mén)、功能強(qiáng)大,在許多領(lǐng)域中都有廣泛的應(yīng)用,例如最熱門(mén)的大數(shù)據(jù)分析,人工智能,Web開(kāi)發(fā)等。
利用seek監(jiān)控文件內(nèi)容,并打印出變化內(nèi)容:
#/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監(jiān)控文件內(nèi)容變化,當(dāng)文件逐漸變大時(shí),可輕松完成任務(wù):
#!/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()
感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“使用Python監(jiān)控文件內(nèi)容變化的方法”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。