python监听文件夹里文件变化

本文介绍了一个Python函数,用于获取指定目录下所有文件的修改时间,并实现持续监听,当文件被修改时检测并记录改动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import operator
import os
import time


def get_timestamp(dir_path):
    # 获取文件夹内所有文件的修改时间
    timestamp = []
    for root, dirs, files in os.walk(dir_path):
        for file in files:
            _file = os.path.join(root, file)  # 构建完整路径
            modify_time_timestamp = os.path.getmtime(_file)  # 获取修改时间戳
            timestamp.append(modify_time_timestamp)
    return timestamp


def timestamp_change(dir_path):
    # 获取文件夹内所有文件的修改时间
    timestamp_old = get_timestamp(dir_path)
    while True:  # 持续监听
        timestamp_new = get_timestamp(dir_path)
        eq = operator.eq(timestamp_old, timestamp_new)  # 比较时间戳是否变化
        if not eq:
            # 当时间戳不一致时将新时间戳转为旧时间戳
            timestamp_old = timestamp_new.copy()
        # yield "data:" + str(req) + "\n\n"  # 独立运行时不添加,需要返回时添加
        time.sleep(2)  # 休息2秒

Python监听文件夹变化并实时将新增或修改的文件信息记录到数据库,通常可以使用`watchdog`库来监控文件系统,结合`sqlite3`等轻量级数据库处理文件名。以下是一个简单的示例: 首先,安装所需库: ```bash pip install watchdog sqlite3 ``` 然后编写一个Python脚本,例如`file_monitor.py`: ```python import time from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler import sqlite3 # 创建数据库连接 conn = sqlite3.connect('file_database.db') cursor = conn.cursor() cursor.execute('''CREATE TABLE IF NOT EXISTS files (filename TEXT PRIMARY KEY)''') class FileHandler(FileSystemEventHandler): def on_modified(self, event): if event.src_path.endswith(('.txt', '.csv')): # 只关注特定类型的文件 with open(event.src_path, 'r') as f: filename = f.name cursor.execute("INSERT INTO files VALUES (?)", (filename,)) conn.commit() def on_created(self, event): if event.is_directory: return with open(event.src_path, 'r') as f: filename = f.name cursor.execute("INSERT INTO files VALUES (?)", (filename,)) conn.commit() # 设置观察者和事件处理器 event_handler = FileHandler() observer = Observer() observer.schedule(event_handler, path='your_watch_folder', recursive=True) try: observer.start() print("开始监听文件夹...") while True: time.sleep(1) except KeyboardInterrupt: observer.stop() print("\n已停止监听,正在保存数据...") conn.close() print("所有更改已保存.") #
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值