脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - 使用Python监视指定目录下文件变更的方法

使用Python监视指定目录下文件变更的方法

2021-04-07 00:40晓东邪 Python

今天小编就为大家分享一篇使用Python监视指定目录下文件变更的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

监视指定目录下文件变更。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# -*- 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监视指定目录下文件变更的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xiaodongxiexie/article/details/79806961

延伸 · 阅读

精彩推荐