python - 删除 Python 中除最新文件夹外的所有文件夹

标签 python python-3.x directory

<分区>

我无法想出一种安全删除提供的根目录中除最近创建或更新的文件夹以外的所有文件夹的方法。我有这个基本的结构设置,但我不确定如何从这里开始:

for root, folders, files in os.walk(output_folder):
    for folder in folders:

最佳答案

你可以这样找到最新的文件夹

import os, shutil

newest_folder = max(folders, key=os.path.getmtime)

for fname in folders:
    if fname != newest_folder:
        shutil.rmtree(folder)

根据您的具体要求,您可能希望使用 getctime 而不是 getmtime

关于python - 删除 Python 中除最新文件夹外的所有文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42196755/

相关文章:

python - AWS Lambda python 库函数错误

python - Django 静态文件不解决常量 404 错误

makefile - 使用 mkdir 时如何防止 makefile 中出现 "directory already exists error"

c# - 将图片从文件导入图片框

python - 用于多个测试的单元测试 setUp/tearDown

python - 为什么 Python 没有隐式转换?

python - 即使在设置 SLUGIFY_USES_TEXT_UNIDECODE 和 AIRFLOW_GPL_UNIDECODE 后也无法安装 Airflow

permissions - Inno Setup-如何设置文件夹的完全权限,而不仅仅是其内容

python - 存储和使用经过训练的神经网络

Python itertools—takewhile() : multiple predicates