求助:如何为Python目录监控脚本添加文件修改且仍被占用提示
检测目录文件变更并识别“修改但仍被占用”的文件
你的原脚本已经能检测文件的新增和删除,要实现修改但仍被占用的提示,我们需要做两个关键改进:
- 跟踪文件的修改时间来判断是否被修改
- 通过尝试以独占方式打开文件,来判断它是否被其他程序占用
下面是修改后的完整脚本,我添加了详细注释说明:
import os import time def is_file_in_use(file_path): """判断文件是否被其他程序占用""" try: # 以独占模式打开文件(Windows下有效),如果被占用会抛出PermissionError with open(file_path, 'r+') as f: return False except PermissionError: return True except Exception as e: # 处理其他可能的异常(比如文件不存在、无读取权限等) return False path_to_watch = r"C:\Users\u104810\Desktop\New folder" # 初始化字典,存储文件名和对应的最后修改时间 before = {f: os.path.getmtime(os.path.join(path_to_watch, f)) for f in os.listdir(path_to_watch) if os.path.isfile(os.path.join(path_to_watch, f))} while True: time.sleep(10) # 重新获取当前目录下的文件及修改时间,只考虑文件(排除文件夹) after = {f: os.path.getmtime(os.path.join(path_to_watch, f)) for f in os.listdir(path_to_watch) if os.path.isfile(os.path.join(path_to_watch, f))} # 检测新增文件 added = [f for f in after if f not in before] if added: print(f"Added: {', '.join(added)}") # 检测删除文件 removed = [f for f in before if f not in after] if removed: print(f"Removed: {', '.join(removed)}") # 检测修改过的文件 modified = [f for f in after if f in before and after[f] != before[f]] if modified: for file_name in modified: file_full_path = os.path.join(path_to_watch, file_name) if is_file_in_use(file_full_path): print(f"{file_name}: modified but still in use") else: print(f"Modified: {file_name}") # 更新before字典为当前状态 before = after
关键改动说明:
- 新增
is_file_in_use函数:通过尝试以读写模式打开文件,如果抛出PermissionError(Windows下文件被占用时会触发),则判断文件正在被使用。 - 跟踪文件修改时间:原脚本只存储文件名,现在改为存储每个文件的最后修改时间
os.path.getmtime(),这样就能对比出哪些文件被修改过。 - 过滤文件夹:添加了
os.path.isfile()判断,只处理文件,避免对文件夹的修改误判。 - 分情况输出修改状态:对修改过的文件,先判断是否被占用,再输出对应的提示信息。
注意:这个方法在Windows系统下效果较好,如果你是在Linux/macOS环境下运行,判断文件是否被占用的逻辑需要调整(比如借助lsof命令),但你的路径是Windows格式,所以我针对Windows做了适配。
内容的提问来源于stack exchange,提问作者Manoj
相关产品推荐
相关产品推荐

