首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何根据python修改的时间删除目录下的子目录?

如何根据python修改的时间删除目录下的子目录?
EN

Stack Overflow用户
提问于 2018-07-15 21:05:26
回答 1查看 42关注 0票数 1

基于此脚本:

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

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-15 21:31:10

你可以沿着这些路线尝试一些东西

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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51348674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档