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

相关文章

pytorch 利用lstm做mnist手写数字识别分类的实例

代码如下,U我认为对于新手来说最重要的是学会rnn读取数据的格式。 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 08:53:25...

django中SMTP发送邮件配置详解

django中SMTP发送邮件配置详解

Django中内置了邮件发送功能,被定义在django.core.mail模块中。发送邮件需要使用SMTP服务器,常用的免费服务器有:163、126、QQ,下面以qq邮箱为例。 注册qq...

Python 和 JS 有哪些相同之处

【嵌牛导读】Python 是一门运用很广泛的语言,自动化脚本、爬虫,甚至在深度学习领域也都有 Python 的身影。作为一名前端开发者,也了解 ES6 中的很多特性借鉴自 Python...

python将一个英文语句以单词为单位逆序排放的方法

例如“I am a boy”,逆序排放后为“boy a am I”所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符。 list_number = list(inpu...

python+selenium识别验证码并登录的示例代码

python+selenium识别验证码并登录的示例代码

由于工作需要,登录网站需要用到验证码。最初是研究过验证码识别的,但是总是不能获取到我需要的那个验证码。直到这周五,才想起这事来,昨天顺利的解决了。 下面正题: python版本:3....