使用Python监视指定目录下文件变更的方法
本文介绍如何利用Python的glob模块递归遍历指定目录,并通过JSON文件持久化记录文件列表,从而检测新增或删除的文件变更。代码包含递归遍历、状态对比及更新逻辑,适用于轻量级目录监控场景。
实现原理与核心逻辑
要实现指定目录下的文件变更监视,核心在于两个步骤:一是获取当前目录下所有文件的完整列表,二是将历史状态与当前状态进行对比。本方案采用递归方式遍历子目录,并将文件路径集合持久化存储为JSON格式,以便后续比对。
递归遍历目录
首先,需要编写一个递归函数来遍历指定根目录下的所有文件和子目录。利用glob.glob配合通配符*可以快速获取当前层级的所有元素。对于子目录,则递归调用自身,确保所有层级的文件都被纳入监控范围。
def penetrate(root: os.path) -> Iterable:
for ele in glob.glob(os.path.join(root, '*')):
if os.path.isdir(ele):
yield ele
yield from penetrate(os.path.abspath(ele))
else:
yield ele状态持久化与对比
为了检测变更,程序需要读取之前保存的文件记录。通过json.load加载历史数据,并与当前遍历得到的文件集合进行集合运算:
- files = s - set(d['files']):计算当前存在但历史记录中没有的文件,即新增文件。
- files2 = set(d['files']) - s:计算历史记录中有但当前不存在的文件,即删除文件。
若检测到新增或删除的文件,则打印相关信息,并更新JSON记录文件,保存最新的文件列表和时间戳。
def update(s: set, exists: bool=False, mode: str='w') -> None or dict :
with open('file_records.json', encoding='utf-8', mode=mode) as file:
if not exists:
json.dump({'datetime': str(datetime.datetime.now()),
'files': list(s)}, file, ensure_ascii=False, indent=10)
else:
return json.load(file)完整代码实现
以下是完整的Python脚本,包含导入模块、递归遍历、状态更新及主逻辑。直接运行该脚本即可对当前目录(或指定root参数)进行文件变更监控。
# -*- coding: utf-8 -*-
# @Author: xiaodong
# @Date: just hide
# @Last Modified by: xiaodong
# @Last Modified time: just hide
import os
import glob
import json
import datetime
from typing import Iterable
"""
监视指定目录下文件变更
"""
def penetrate(root: os.path) -> Iterable:
for ele in glob.glob(os.path.join(root, '*')):
if os.path.isdir(ele):
yield ele
yield from penetrate(os.path.abspath(ele))
else:
yield ele
def update(s: set, exists: bool=False, mode: str='w') -> None or dict :
with open('file_records.json', encoding='utf-8', mode=mode) as file:
if not exists:
json.dump({'datetime': str(datetime.datetime.now()),
'files': list(s)}, file, ensure_ascii=False, indent=10)
else:
return json.load(file)
def main(s: set=set(), root: os.path='.')-> None:
for path in penetrate(root):
s.add(path)
if not os.path.exists('file_records.json'):
update(s)
else:
d = update(None, True, 'r')
files = s - set(d['files'])
files2 = set(d['files']) - s
if files:
print('增加文件: ', files)
if files2:
print('删除文件: ', files2)
if files or files2:
update(s)
print('更新成功!')
if __name__ == "__main__":
main()注意事项
该方案适用于轻量级的文件监控需求。由于每次运行都会重新遍历整个目录,对于文件数量极大或目录层级极深的场景,性能可能会有所下降。此外,该脚本仅检测文件的增删,不检测文件内容的修改。若需监控内容变更,需结合文件哈希值或最后修改时间进行更复杂的逻辑判断。
以上就是使用Python监视指定目录下文件变更的详细内容,更多关于Python文件监控的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













