-
Python 脚本清理 WorkBuddy 空文件夹:定时任务自动删除空目录
背景 在使用 WorkBuddy 一段时间后,我发现工作目录下堆积了大量空文件夹。这些空目录可能是项目删除后残留的,也可能是某些工具自动生成后未清理的。手动一个个删除太麻烦,于是写了一个 Python 脚本来批量清理。 脚本功能 这个脚本有以下特点: 代码实现 """清理当前用户 WorkBuddy 目录下的空文件夹(含级联后的空父目录)。 规则: - 只删除「整棵子树不含任何文件」的目录,目录内只要有文件就一律不动。 - 跳过路径中含 .git / node_modules / app.asar.unpacked 的目录。 - 不加 --apply 只扫描出报告,不删除。 - 删除结果追加写入日志文件。 用法: python clean-empty-dirs.py # 只扫描 python clean-empty-dirs.py --apply # 扫描并删除 """ import os import sys from datetime import datetime USER_HOME = os.path.expanduser("~") ROOT = os.path.join(USER_HOME, "WorkBuddy") LOG_FILE = os.path.join(USER_HOME, ".workbuddy", "logs", "clean-empty-dirs.log") SKIP_SEGMENTS = {".git", "node_modules", "app.asar.unpacked"} def skipped(path): """检查路径是否包含需要跳过的目录段""" return bool(SKIP_SEGMENTS & set(path.split(os.sep))) def log(line): """输出到控制台并追加写入日志文件""" print(line) try: os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True) with open(LOG_FILE, "a", encoding="utf-8") as f: f.write(line + "\n") except OSError: pass def main(): """主函数:扫描空目录并根据参数决定是否删除""" apply = "--apply" in sys.argv # 第一轮:直接为空的目录 empty = [] total_dirs = 0 for cwd, dirs, files in os.walk(ROOT): total_dirs += len(dirs) for d in dirs: full = os.path.join(cwd, d) if skipped(full): continue try: if not os.listdir(full): empty.append(full) except OSError as e: log(f"[跳过] {full} -> {e}") empty_set = set(empty) # 迭代:子目录被删后父目录也可能变空(父目录本身仍不含任何文件) changed = True while changed: changed = False for cwd, dirs, files in os.walk(ROOT): if files or cwd == ROOT or skipped(cwd): continue try: remaining = [n for n in os.listdir(cwd) if os.path.join(cwd, n) not in empty_set] except OSError: continue if not remaining and cwd not in empty_set: empty_set.add(cwd) changed = True stamp =…- 3
- 0

