使用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中bs4.BeautifulSoup的基本用法

导入模块 from bs4 import BeautifulSoup soup = BeautifulSoup(html_doc,"html.parser") 下面看下常见的用...

Python线性回归实战分析

Python线性回归实战分析

一、线性回归的理论 1)线性回归的基本概念 线性回归是一种有监督的学习算法,它介绍的自变量的和因变量的之间的线性的相关关系,分为一元线性回归和多元的线性回归。一元线性回归是一个自变量和一...

解决python opencv无法显示图片的问题

解决python opencv无法显示图片的问题

结合网上解决方法,总结了一下 注意三点: 1.文件名或路径名开头如果会引起转义,则\要替换为\\ 2.文件不能放在桌面,因为读取时按中文路径 3.运行后未响应,原因还没有查明,在下一行...

Django框架之登录后自定义跳转页面的实现方法

Django auth 登陆后页面跳转至/account/profile,修改跳转至其他页面 这几天在学习django,django功能很强大,自带的auth,基本可以满足用户注册登陆登...

python RC4加密操作示例【测试可用】

python RC4加密操作示例【测试可用】

本文实例讲述了python RC4加密操作。分享给大家供大家参考,具体如下: # -*- conding:utf-8 -*- from Crypto.Cipher import AR...