MCPcopy Create free account
hub / github.com/QWTforGithub/T2LDM / remove_empty_dirs

Function remove_empty_dirs

utils/common.py:352–392  ·  view source on GitHub ↗

递归删除 `root` 下的所有空文件夹(自底向上)。 Args: root: 根目录路径 remove_root: 若最终 root 也为空,是否一并删除 Returns: deleted: 实际删除的目录 Path 列表(按删除顺序)

(
        root: str | Path, *,
        remove_root: bool = False
)

Source from the content-addressed store, hash-verified

350 return weights
351
352def remove_empty_dirs(
353 root: str | Path, *,
354 remove_root: bool = False
355) -> List[Path]:
356 """
357 递归删除 `root` 下的所有空文件夹(自底向上)。
358 Args:
359 root: 根目录路径
360 remove_root: 若最终 root 也为空,是否一并删除
361 Returns:
362 deleted: 实际删除的目录 Path 列表(按删除顺序)
363 """
364 root = Path(root).resolve()
365 deleted: List[Path] = []
366 if not root.exists() or not root.is_dir():
367 return deleted
368
369 # 多轮自底向上:先清理叶子,再尝试其父级
370 # Path.rglob('*') 会列出所有层级,按长度倒序确保“先子后父”
371 for p in sorted(root.rglob('*'), key=lambda x: len(x.parts), reverse=True):
372 # 只处理“真实目录”(跳过符号链接目录)
373 if p.is_dir() and not p.is_symlink():
374 try:
375 # 目录为空才能 rmdir
376 if not any(p.iterdir()):
377 p.rmdir()
378 deleted.append(p)
379 except PermissionError:
380 pass # 无权限时跳过
381 except OSError:
382 pass # 并发/瞬时写入导致非空等,忽略
383
384 # 最后处理根目录
385 if remove_root and not any(root.iterdir()):
386 try:
387 root.rmdir()
388 deleted.append(root)
389 except Exception:
390 pass
391
392 return deleted
393
394def w_smooth(
395 depth_pred,

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected