You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python结合watchdog快速查询指定时间段内新增的文件?

可行解决方案

方案1:watchdog常驻监控+轻量索引(推荐,完全避免全量扫描)

核心逻辑是用常驻进程监听目录变更,提前将新增文件信息存入本地索引,查询时直接读取索引即可,不需要每次扫描全量文件。

实现步骤

  • 编写常驻监控脚本,用watchdog监听目标目录的文件创建事件,实时将文件路径、文件名、创建时间戳写入本地轻量数据库(比如SQLite)
  • 首次启动监控时如果需要历史数据,可仅扫描指定时间段内的文件入库,不需要全量录入所有存量文件
  • 查询时直接筛选索引中创建时间符合要求的记录即可,响应时间在毫秒级

监控端核心代码

import time
import sqlite3
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# 初始化索引数据库
conn = sqlite3.connect('file_index.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS files
             (path TEXT PRIMARY KEY, filename TEXT, create_time REAL)''')
conn.commit()

class FileCreateHandler(FileSystemEventHandler):
    def on_created(self, event):
        if not event.is_directory:
            c.execute("INSERT OR REPLACE INTO files VALUES (?, ?, ?)",
                      (event.src_path, event.src_path.split('/')[-1], time.time()))
            conn.commit()

if __name__ == "__main__":
    event_handler = FileCreateHandler()
    observer = Observer()
    # recursive参数根据是否需要监听子目录调整
    observer.schedule(event_handler, path="/你的目标目录路径", recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
    conn.close()

查询端代码

import sqlite3
import time

conn = sqlite3.connect('file_index.db')
c = conn.cursor()
# 筛选过去24小时内创建的文件
cutoff_timestamp = time.time() - 86400
c.execute("SELECT path, filename FROM files WHERE create_time >= ?", (cutoff_timestamp,))
target_files = c.fetchall()
conn.close()

方案2:调用系统原生文件查询工具(无需常驻服务,比自行Python遍历快10~100倍)

如果不想运行常驻进程,直接调用操作系统原生的文件查询命令,效率远高于自己用Python实现全量遍历,45万文件的查询耗时通常在30秒以内。

Linux/macOS环境调用示例

import subprocess

target_dir = "/你的目标目录路径"
# 调用find命令查询过去24小时内创建的文件
cmd = f'find {target_dir} -type f -newermt "24 hours ago"'
all_recent_files = subprocess.check_output(cmd, shell=True).decode().splitlines()
# 额外过滤文件名包含指定日期的目标文件
target_files = [f for f in all_recent_files if '目标日期字符串' in f]

Windows环境可替换为调用dir命令或PowerShell的Get-ChildItem指令实现相同效果。

方案3:目录结构优化(根源解决问题,可调整写入逻辑时优先选择)

如果有权限修改文件写入规则,直接按日期分层存储文件,比如路径规则设置为/根目录/年/月/日/文件名,当日写入的文件全部落到对应日期的子目录下,查询时直接遍历该子目录即可,完全不需要碰其他日期的文件。

内容的提问来源于stack exchange,提问作者jB777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 12:24:02