python - 如何使用python根据修改时间删除目录中的子目录?

标签 python delete-directory

基于此脚本:

 #!/usr/bin/python

# run by crontab
# removes any files in /tmp/ older than 7 days

import os, sys, time
from subprocess import call

now = time.time()
cutoff = now - (7 * 86400)

files = os.listdir("/tmp")
for xfile in files:
        if os.path.isfile( "/tmp/" + xfile ):
                t = os.stat( "/tmp/" + xfile )
                c = t.st_ctime

                # delete file if older than a week
                if c < cutoff:
                        os.remove("/tmp/" + xfile)

我们可以根据修改时间删除某个路径中的文件,但是如何根据修改时间删除其他文件夹中的文件夹呢?

这意味着主文件夹中有很多文件夹,但我们需要保留主文件夹和子文件夹,并且只删除修改时间早于特定时间的文件夹。

最佳答案

你可以尝试一下这些方法

import shutil, os, time

top_dir = '/tmp'

now = time.time()
cutoff = now - (7 * 86400)

def del_old_files_and_dirs(top_dir, cutoff_time):
    for root, dirs, files in os.walk(top_dir, topdown=False):
        for cdir in dirs:
            fdir = os.path.join(root, cdir)
            if os.path.getmtime(fdir) < cutoff_time:
                shutil.rmtree(fdir)
            else:
                # Process this dir again recursively
                del_old_files_and_dirs(fdir, cutoff_time)
        for cfile in files:
            ffile = os.path.join(root, cfile)
            if os.path.getmtime(ffile) < cutoff_time:
                  os.remove(ffile)



del_old_files_and_dirs(top_dir, cutoff)

关于python - 如何使用python根据修改时间删除目录中的子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51348674/

相关文章:

java - 在Java中递归删除目录

file - 如何使用 PowerShell 删除空子文件夹?

python - "%"登录 matplotlib Python

windows - 如何使用 PowerShell 2.0 递归删除整个目录?

python - Scrapy - 由于编码而无法跟踪链接

Pandas 系列的python键值列表

vb.net - 删除 vb.net 中的子文件夹和文件

powershell - 在5GB可用空间可用之前,如何删除LRU文件夹?

python - 将 pandas 数据透视表转换为二维数组

python - 即使 dataFrame 为空,也将 headers 保留在 groupby 过滤中