使用Python监视文件变化

网上有很多例子都太过复杂了,其实只要观察文件的最后修改时间是否变动,就能判断文件是否变化了

# Runtime: Python 3.9.6
import os
from time import sleep

_path = __file__[::-1]

idx = _path.find("/")
dir = _path[idx + 1 :][::-1]

exclude = ["ignored_directory", __file__[len(dir) :]]
map = dict()


def scan(file_name: str):
    if os.path.isdir(file_name):
        for s in os.listdir(file_name):
            if s in exclude:
                continue
            s = f"{file_name}/{s}"
            scan(s)
        return

    mtime = float(os.stat(file_name).st_mtime)
    cache_time = map.get(file_name)

    # if file_name.endswith('.test'):
    #     print(mtime, cache_time)

    if not cache_time or cache_time < mtime:
        print("Detected file changes:", file_name)
        handle_file(file_name)
        map[file_name] = mtime
    return


def handle_file(file_path):
    # Do your bussiness here
    pass


while True:
    scan(dir)
    sleep(1)