【问题标题】:How to delete sub directories in a directory based on their time modified by using python?如何根据使用python修改的时间删除目录中的子目录?
【发布时间】:2018-12-23 05:24:05
【问题描述】:

基于此脚本:

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

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

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

【问题讨论】:

    标签: python delete-directory


    【解决方案1】:

    你可以尝试这些方法

    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)
    

    【讨论】:

    • 我运行它但它有一个错误:TypeError: coercing to Unicode: need string or buffer, list found
    • 至少缺少两个)xfile 应该是 cfile - 在发布之前尝试你的代码 :)
    • 现在它不会产生错误,但它什么也不做!
    • 现已修复...再试一次
    • @ack。对此感到抱歉。现在应该修复了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多