在Python中删除旧目录

时间:2010-02-10 15:23:29

标签: python time directory timestamp

我有几个目录,我希望删除超过7天的目录。我已经实现了代码,但它似乎没有工作。谁能看到我错在哪里?

def delete_sandbox():

    for directories in os.listdir(os.getcwd()): 

        if not os.path.isdir(directories) or not os.stat(directories).st_ctime < time.time()-(7*24*3600): 
            continue
        os.chdir(directories)
        drop_sandbox()
        os.chdir(rootDir)
        os.system("sudo rm -rf "+directories)
        print 'Folders older than 7 days old dropped and removed'

感谢您的帮助

文件夹沙箱会丢弃,但不会删除。我希望程序进入这些文件夹中的每一个,将沙箱,chnage放回根目录并删除所有旧目录。当我这样做时,文件夹仍然存在。

当我通过存储在文件夹名称中的字符串日期删除目录时,此功能也起作用。但现在我正试图获取时间戳,它已停止工作。

我测试了'rm -rf'+directories并且它没有删除旧文件夹。当我尝试shutil.rmtree时,收到错误消息:

Traceback (most recent call last):
  File "yep.py", line 21, in <module>
    delete_sandbox()
  File "yep.py", line 18, in delete_sandbox
    shutil.rmtree(directories)
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 208, in rmtree
    onerror(os.listdir, path, sys.exc_info())
  File "/home/build/workspace/downloads/Python-2.6.4/Lib/shutil.py", line 206, in rmtree
    names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'Debug'

还有其他方法可以删除这些文件夹吗?

我得到了它的工作,我使用shutil.rmtree,似乎一切正常。谢谢你的帮助。修改后的代码是:

def delete_sandbox():

    for directories in os.listdir(os.getcwd()): 

        if not os.path.isdir(directories) or not os.stat(directories).st_ctime < time.time()-(sbox_age): 
            continue
        os.chdir(directories)
        drop_sandbox()
        os.chdir(rootDir)
        shutil.rmtree(directories)
        print 'Sandboxes older than 7 days old dropped and removed'

delete_sandbox()

4 个答案:

答案 0 :(得分:9)

import os
import time
import shutil
numdays = 86400*7
now = time.time()
directory=os.path.join("/home","path")
for r,d,f in os.walk(directory):
    for dir in d:
         timestamp = os.path.getmtime(os.path.join(r,dir))
         if now-numdays > timestamp:
             try:
                  print "removing ",os.path.join(r,dir)
                  # shutil.rmtree(os.path.join(r,dir))  #uncomment to use
             except Exception,e:
                  print e
                  pass
             else: 
                  print "some message for success"

答案 1 :(得分:1)

os.listdir返回字符串列表,这些字符串是相对路径。当您使用rootdir时,取决于rootDir,这些路径可能不再有效。

答案 2 :(得分:1)

  • drop_sandbox()做什么? (你给我们的函数是delete_sandbox())也许你的意思是这是一个递归函数并使用了错误的函数名称
  • rootDir是全局变量吗?也许你的意思是os.chdir("..")
  • rootDir包含哪些内容? os.listdir给出了相对路径。如果rootDir是您搜索的基础,则您列出的目录可能无效。更糟糕的是:如果他们这样做,你可能会删除你仍想要的东西。

此外,shutil包具有您可能想要查看的rmtree功能。

答案 3 :(得分:0)

虽然接受的答案的一般概念是合理的,但实施有几点不是。

  1. 字符不收取变量名称。
  2. 请不要覆盖像dir()
  3. 这样的python方法

    由于我需要更多功能,我接受了你的想法并构建了这个:

    class CompRM(object):
        exception_list = []
        path = None
        comparator = None
        comparator_target = None
        comparator_delete_condition = None
    
        delete_directories = False
        delete_files = False
    
        def __init__(self, target_path, comparator, comparator_target='st_mtime', comparator_delete_condition='>', delete_directories=False, delete_files=False):
            self.path = target_path
            self.comparator = comparator
            self.comparator_target = comparator_target
            self.comparator_delete_condition = comparator_delete_condition
    
            for directory_path, directory_names, file_names in os.walk(self.path):
                if delete_directories is True:
                    self.walk_names(directory_path, directory_names)
                if delete_files is True:
                    self.walk_names(directory_path, file_names)
    
            if len(self.exception_list) > 0:
                raise Exception({'message': 'Encountered exceptions while deleting.', 'debug': self.exception_list})
    
        def walk_names(self, directory_path, names):
            for _name in names:
                _path = os.path.join(directory_path, _name)
                _stat = os.stat(_path)
                _value = getattr(_stat, self.comparator_target)
                if self.delete_condition_met(_value):
                    self.safe_remove(_path)
    
        def delete_condition_met(self, value):
            if self.comparator > value and self.comparator_delete_condition is '>':
                return True
            if self.comparator < value and self.comparator_delete_condition is '<':
                return True
            return False
    
        def safe_remove(self, remove_path):
            print 'remove', remove_path
            shutil.rmtree(remove_path, onerror=self.register_exception)
    
        def register_exception(self, function, path, exception_info):
            self.exception_list.append({
                function: function,
                path: path,
                exception_info: exception_info,
            })
    

    您可以这样称呼它:

    comprm = CompRM('/tmp', time.time() - 60*60*24*7, comparator_target='st_ctime', delete_files=True)
    

    其中comparator_target是os.stat()中的属性名,用于比较。

    此致 贾斯特斯