SoFunction
Updated on 2024-11-13

Ways to monitor file changes in a given directory using Python

Monitors file changes in the specified directory.

# -*- 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

"""
Monitor file changes in a specified directory
"""

def penetrate(root: ) -> Iterable:
 for ele in ((root, '*')):
 if (ele):
  yield ele
  yield from penetrate((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:
  ({'datetime': str(()),
   'files': list(s)}, file, ensure_ascii=False, indent=10)
 else:
  return (file)


def main(s: set=set(), root: ='.')-> None:
 for path in penetrate(root):
 (path)

 if not ('file_records.json'):
 update(s)
 else:
 d = update(None, True, 'r')
 files = s - set(d['files'])
 files2 = set(d['files']) - s
 if files:
  print('Addition of documents:', files)
 if files2:
  print('Delete file:', files2)
 if files or files2:
  update(s)
  print('Update successful!')


if __name__ == "__main__":
 main()

The above method of using Python to monitor file changes in a specified directory is all that I have shared with you.