使用Python监视指定目录下文件变更的方法

yipeiwu_com5年前Python基础

监视指定目录下文件变更。

# -*- 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设计】。

相关文章

对numpy中的where方法嵌套使用详解

如同for循环一样,numpy中的where方法可以实现嵌套功能。这是简化嵌套式矩阵逻辑的一个很好的方法。 假设有一个矩阵,需要把小于0的元素改成-1,大于0的元素改成1,而等于0的时候...

Python代码生成视频的缩略图的实例讲解

Reddit 上目前充斥着各种机器人账号,官方也非常支持这种行为,只要不是无意义的发言,机器人多了还能增加活跃度,吸引真人用户一起来各抒己见,比如说每周都有的一个“烦人的星期二”的帖子,...

详解如何管理多个Python版本和虚拟环境

多个Python版本:在同一台机器上安装不同的Python,例如2.7和3.4。 虚拟环境:独立的环境,既可以同时安装特定版本的Python,也可以安装任何特定于项目的软件包,而不会影...

Python全排列操作实例分析

本文实例讲述了Python全排列操作。分享给大家供大家参考,具体如下: step 1: 列表的全排列: 这个版本比较low # -*-coding:utf-8 -*- #!pytho...

浅析Python中的多重继承

浅析Python中的多重继承

继承是面向对象编程的一个重要的方式,因为通过继承,子类就可以扩展父类的功能。 回忆一下Animal类层次的设计,假设我们要实现以下4种动物:    ...