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

相关文章

运行django项目指定IP和端口的方法

运行django项目指定IP和端口的方法

一、django项目启动命令 默认IP和端口 python manage.py runserver 指定端口 python manage.py runserver 192.1...

学习Python3 Dlib19.7进行人脸面部识别

学习Python3 Dlib19.7进行人脸面部识别

0.引言 自己在下载dlib官网给的example代码时,一开始不知道怎么使用,在一番摸索之后弄明白怎么使用了; 现分享下 face_detector.py 和&n...

Python实现的最近最少使用算法

本文实例讲述了Python实现的最近最少使用算法。分享给大家供大家参考。具体如下: # lrucache.py -- a simple LRU (Least-Recently-Use...

利用python3随机生成中文字符的实现方法

前言 运行环境在Python3.6下,Python2的解决方案网上有很多.,想学习python2实现的朋友们可以参考这篇文章:/post/34884.htm,下面来一起看看详细的介绍吧。...

pandas计数 value_counts()的使用

pandas计数 value_counts()的使用

在pandas里面常用value_counts确认数据出现的频率。 1. Series 情况下: pandas 的 value_counts() 函数可以对Series里面的每个值进行计...