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

如何在Python中将文件修改状态转为布尔值用于IF语句?

基于文件修改日期触发任务的实现方法

要实现文件/目录修改时自动执行任务,核心思路是记录上次的修改时间,定期对比当前修改时间,发现变化就触发任务。os.path.getmtime返回的是时间戳(数字),完全可以用在if语句里做比较,关键是要有一个参照的“上次时间”。

方法一:监控整个目录(含新增/修改文件)

如果要监控目录下所有文件的变化(包括新增文件、修改已有文件),可以用轮询的方式定期检查:

import os
import time

def monitor_directory(dir_path, task_func, check_interval=5):
    # 初始化记录目录内所有文件的修改时间
    last_modified_times = {}
    # 先获取初始状态
    for filename in os.listdir(dir_path):
        full_path = os.path.join(dir_path, filename)
        if os.path.isfile(full_path):
            last_modified_times[full_path] = os.path.getmtime(full_path)
    
    while True:
        current_modified_times = {}
        has_change = False
        # 遍历目录,检查每个文件的当前修改时间
        for filename in os.listdir(dir_path):
            full_path = os.path.join(dir_path, filename)
            if os.path.isfile(full_path):
                current_mtime = os.path.getmtime(full_path)
                current_modified_times[full_path] = current_mtime
                # 判断是否有新文件或文件被修改
                if full_path not in last_modified_times or current_mtime > last_modified_times[full_path]:
                    has_change = True
        
        # 有变化则执行任务,更新记录的时间
        if has_change:
            task_func()
            last_modified_times = current_modified_times.copy()
        
        # 间隔指定秒数后再次检查
        time.sleep(check_interval)

# 你要执行的任务函数示例
def do_xyz():
    print("检测到文件修改,执行指定任务...")

# 启动监控
if __name__ == "__main__":
    monitor_directory('C:/Hi/', do_xyz, check_interval=5)

方法二:监控单个文件

如果只需要监控某个特定文件的修改,代码会更简洁:

import os
import time

def monitor_single_file(file_path, task_func, check_interval=5):
    # 初始化上次修改时间,文件不存在则设为0
    last_mtime = os.path.getmtime(file_path) if os.path.exists(file_path) else 0
    
    while True:
        if os.path.exists(file_path):
            current_mtime = os.path.getmtime(file_path)
            # 对比当前和上次的修改时间,发现更新则触发任务
            if current_mtime > last_mtime:
                task_func()
                last_mtime = current_mtime
        time.sleep(check_interval)

# 启动单个文件监控
monitor_single_file('C:/Hi/target.txt', do_xyz)

关键说明

  • os.path.getmtime返回的是Unix时间戳(从1970年1月1日到现在的秒数),是数字类型,直接用>就能比较新旧
  • 检查间隔check_interval可以根据需求调整:太小会占用CPU资源,太大可能延迟检测到文件修改
  • 如果需要更高效的实时监控(不用轮询),可以考虑使用第三方库如watchdog,但上面的轮询方法无需额外依赖,足够应对多数简单场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:01:13