使用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的Flask框架来构建一个简单的数字商品支付解决方案

利用Python的Flask框架来构建一个简单的数字商品支付解决方案

作为一个程序员,我有时候忘了自己所具有的能力。当事情没有按照你想要的方式发展时,却很容易忘记你有能力去改变它。昨天,我意识到,我已经对我所出售的书的付款处理方式感到忍无可忍了。我的书完成...

PyQt5 窗口切换与自定义对话框的实例

近日,需要实现一个功能小而全的桌面版软件,所以选中并尝试了PyQt5这个GUI库。在使用中发现,其功能的确完备,但这方面的资料的确不多,有时自己想实现的功能相关资料找不到,有的还不得不阅...

Python实现合并两个列表的方法分析

本文实例讲述了Python实现合并两个列表的方法。分享给大家供大家参考,具体如下: 浏览博客看到一个问题:如何合并两个列表,今天就来探讨一下。 方法一 最原始,最笨的方法,分别从两个列表...

浅谈python 读excel数值为浮点型的问题

如下所示: #读入no data = xlrd.open_workbook("no.xlsx") #打开excel table = data.sheet_by_name("Sheet...

初次部署django+gunicorn+nginx的方法步骤

环境 ubuntu16.04 python3.6 django1.11 gunicorn19.7.1 nginx1.10.3 写在前面 其实无论是在部署,还是在其他方面,我们总会遇到一...