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

yipeiwu_com6年前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 PyInstaller库基本使用方法分析

Python PyInstaller库基本使用方法分析

本文实例讲述了Python PyInstaller库基本使用方法。分享给大家供大家参考,具体如下: 概述 将.py源码转换成无需源代码的可执行文件 .py文件 -> PyIns...

基于Python对数据shape的常见操作详解

这一阵在用python做DRL建模的时候,尤其是在配合使用tensorflow的时候,加上tensorflow是先搭框架再跑数据,所以调试起来很不方便,经常遇到输入数据或者中间数据sha...

Python处理命令行参数模块optpars用法实例分析

本文实例讲述了Python处理命令行参数模块optpars用法。分享给大家供大家参考,具体如下: optpars是python中用来处理命令行参数的模块,可以自动生成程序的帮助信息,功能...

python利用Tesseract识别验证码的方法示例

python利用Tesseract识别验证码的方法示例

无论是是自动化登录还是爬虫,总绕不开验证码,这次就来谈谈python中光学识别验证码模块tesserocr和pytesseract。tesserocr和pytesseract是Pytho...

用Python删除本地目录下某一时间点之前创建的所有文件的实例

因为工作原因,需要定期清理某个文件夹下面创建时间超过1年的所有文件,所以今天集中学习了一下Python对于本地文件及文件夹的操作。网上 这篇文章 简明扼要地整理出最常见的os方法,抄袭如...