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

相关文章

Pycharm学习教程(3) 代码运行调试

Pycharm学习教程(3) 代码运行调试

Pycharm代码运行调试,具体内容如下 1、准备工作   (1)Python版本为2.7或者更高版本   (2)已经创建了一个Python工程并且添加了内容,具体参考: Getting...

使用Python的networkx绘制精美网络图教程

使用Python的networkx绘制精美网络图教程

最近因为数学建模3天速成Python,然后做了一道网络的题,要画网络图。在网上找了一些,发现都是一些很基础的丑陋红点图,并且关于网络的一些算法也没有讲,于是自己进http://netwo...

利用Python正则表达式过滤敏感词的方法

利用Python正则表达式过滤敏感词的方法

问题描述:很多网站会对用户发帖内容进行一定的检查,并自动把敏感词修改为特定的字符。 技术要点: 1)Python正则表达式模块re的sub()函数; 2)在正则表达式语法中,竖线“|”表...

Django MEDIA的配置及用法详解

Django MEDIA的配置及用法详解

如果需要在数据库中存储图片或视频类的数据,我们可以配置MEDIA. 下面的示例将以上传一张图片的形式来说明MEDIA的配置及用法. 第一步 settings.py # media配置...

在python3环境下的Django中使用MySQL数据库的实例

在python3环境下的Django中使用MySQL数据库的实例

我们在使用Django过程中,数据库往往是离不开的,比较长常用的是MySQL数据库,但在使用过程中,对Python不同的版本对用的库也不一样,用惯了Python2的人在使用Python3...