Python3判断文件是否已经更新
一、os模块的stat方法
Python3中的os模块提供了stat方法,可以返回文件的状态信息,包括文件大小、创建时间、访问时间和修改时间等。通过获取文件的修改时间和记录的上次修改时间比对,即可判断文件是否更新。
```
import os
import time
filename = 'test.txt'
#获取文件的状态信息
stat_info = os.stat(filename)
#获取文件的修改时间
modify_time = stat_info.st_mtime
#将修改时间转化为可读格式
modify_time_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modify_time))
#记录上次修改时间
last_modify_time = modify_time
#每隔一分钟检查一次文件是否更新
while True:
stat_info = os.stat(filename)
modify_time = stat_info.st_mtime
if modify_time != last_modify_time:
#文件已更新,进行相应的处理
print('文件已更新,上次修改时间为:%s,本次修改时间为:%s' % (modify_time_str, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(modify_time))))
last_modify_time = modify_time
time.sleep(60)
```
二、hashlib模块的md5方法
除了可以通过获取文件的修改时间判断文件是否更新外,还可以通过对文件进行hash计算的方法进行判断。Python3中的hashlib模块提供了md5方法,可以对文件进行md5计算,通过比对上次计算的md5值和本次计算的md5值,即可判断文件是否更新。
```
import hashlib
import time
filename = 'test.txt'
#获取文件的md5值
def get_md5(file):
md5_obj = hashlib.md5()
with open(file, 'rb') as f:
while True:
data = f.read(4096)
if not data:
break
md5_obj.update(data)
md5 = md5_obj.hexdigest()
return md5
#记录上次md5值
last_md5 = get_md5(filename)
#每隔一分钟检查一次文件是否更新
while True:
current_md5 = get_md5(filename)
if current_md5 != last_md5:
#文件已更新,进行相应的处理
last_md5 = current_md5
time.sleep(60)
```
三、watchdog库
可以使用Python3的第三方库watchdog来监控文件的变化并进行相应的处理。watchdog支持监控文件和文件夹的变化,可以自定义处理程序。
```
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
#监控文件更新事件
class FileHandler(FileSystemEventHandler):
def on_modified(self, event):
#文件已更新,进行相应的处理
print('文件已更新:%s' % event.src_path)
filename = 'test.txt'
#创建监控对象
observer = Observer()
event_handler = FileHandler()
observer.schedule(event_handler, path='./', recursive=False)
#启动监控
observer.start()
#每隔一分钟检查一次是否退出程序
while True:
time.sleep(60)
if not observer.is_alive():
#程序已退出
break
#关闭监控
observer.stop()
observer.join()
```
我的笔记