使用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使用time模块实现指定时间触发器示例

Python使用time模块实现指定时间触发器示例

本文实例讲述了Python使用time模块实现指定时间触发器。分享给大家供大家参考,具体如下: 其实很简单,指定某个时间让脚本处理一个事件,比如说一个get请求~ 任何语言都会有关于时间...

python 读取.csv文件数据到数组(矩阵)的实例讲解

利用numpy库 (缺点:有缺失值就无法读取) 读: import numpy my_matrix = numpy.loadtxt(open("1.csv","rb"),delim...

Python NumPy库安装使用笔记

1. NumPy安装 使用pip包管理工具进行安装 复制代码 代码如下: $ sudo pip install numpy 使用pip包管理工具安装ipython(交互式shell工具...

pyqt4教程之实现windows窗口小示例分享

复制代码 代码如下:import sysfrom PyQt4 import QtGui, QtCoreclass Window( QtGui.QMainWindow): &nb...

详解如何在python中读写和存储matlab的数据文件(*.mat)

背景 在做deeplearning过程中,使用caffe的框架,一般使用matlab来处理图片(matlab处理图片相对简单,高效),用python来生成需要的lmdb文件以及做test...