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

How to delete sub directories in a directory based on their time modified by using python?

基于此脚本:

 #!/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)