使用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设计】。

相关文章

学习python中matplotlib绘图设置坐标轴刻度、文本

学习python中matplotlib绘图设置坐标轴刻度、文本

总结matplotlib绘图如何设置坐标轴刻度大小和刻度。 上代码: from pylab import * from matplotlib.ticker import Multi...

详解Python3 基本数据类型

详解Python3 基本数据类型

Python3 基本数据类型 Python 中的变量不需要声明。每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。 在 Python 中,变量就是变量,它没有类型,我们所说的"类...

Python中的异常处理try/except/finally/raise用法分析

本文实例分析了Python中的异常处理try/except/finally/raise用法。分享给大家供大家参考,具体如下: 异常发生在程序执行的过程中,如果python无法正常处理程序...

Django中使用 Closure Table 储存无限分级数据

这篇文章给大家介绍Django中使用 Closure Table 储存无限分级数据,具体内容如下所述: 起步 对于数据量大的情况(比如用户之间有邀请链,有点三级分销的意思),就要用到 c...

Django中cookie的基本使用方法示例

前言 基于 Internet的各种服务系统应运而生,建立商业站点或者功能比较完善的个人站点,常常需要记录访问者的一些信息;论坛作为 Internet发展的产物之一,在 Internet...