使用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函数设计规范详解

Python函数的设计规范 1、Python函数设计时具备耦合性和聚合性 1)、耦合性: (1).尽可能通过参数接受输入,以及通过return产生输出以保证函数的独立性; (2).尽量减...

Python使用combinations实现排列组合的方法

好久没有写博客了!昨天小牛在上海举办了牛友见面会,现场优惠还是比较大,心仪已久加上一时脑热就入手了。以为会有多么开心,其实目前最大的感受就是焦虑!担心电动车被偷,担心电池被偷,担心路上突...

Python基于二分查找实现求整数平方根的方法

本文实例讲述了Python基于二分查找实现求整数平方根的方法。分享给大家供大家参考,具体如下: x=int(raw_input('please input a int:')) if...

Python入门之modf()方法的使用

 modf()方法返回两个项的元组x的整数小数部分。这两个元组具有相同x符号。则返回一个浮点数的整数部分。 语法 以下是modf()方法的语法: import math...

Python实现数据结构线性链表(单链表)算法示例

Python实现数据结构线性链表(单链表)算法示例

本文实例讲述了Python实现数据结构线性链表(单链表)算法。分享给大家供大家参考,具体如下: 初学python,拿数据结构中的线性链表存储结构练练手,理论比较简单,直接上代码。 #...