zoukankan      html  css  js  c++  java
  • 根据正则表达式来清理文件夹

    http://www.cnblogs.com/itech/archive/2011/03/22/1991756.html

    清除指定目录下的子文件, 只保留与给定的正则表达式匹配且最后创建的N个。

    代码:

    复制代码
    import os
    import sys
    import re
    import shutil


    def cleanUp(dir, regrex, num):
      if not os.path.exists(dir) and not os.path.isdir(dir) : 
        print 'path %s is not existed or is not a directory' %dir
        return False

      subfolderdict = {}
      for subI in os.listdir(dir):
        sf = os.path.join(dir,subI)
        if os.path.isdir(sf) and not re.match(regrex, subI) == None:
          sftime = os.path.getctime(sf)
          subfolderdict[sftime] = sf
        else:
          continue

      subfolders = subfolderdict.keys()
      if len(subfolders) == 0 : return True
          
      subfolders.sort(reverse=True)
      n = int(num)
      if len(subfolders) >= n :
        subfolders = subfolders[n:]
      elsereturn True

      if len(subfolders) == 0 : return True
      
      for sftime in subfolders:
        sf = subfolderdict[sftime]
        #shutil.rmtree(sf)
        print '%s is removed' % sf

      return True


    def usage():
      usage = '
      Function:
        Clean Up subfolders in (dir), as a result :
        just keep the subfolders which are matched with (regrex), 
        and the number of the subfoler cannot more then (num).
      Usage:
        python %s dir regrex num
      ' %sys.argv[0]
      print usage


    if __name__ == '__main__':
      if len(sys.argv) == 4 :
        cleanUp(sys.argv[1],sys.argv[2],sys.argv[3])
      else:
        usage()
    复制代码
  • 相关阅读:
    如何计算两个日期之间相差天数
    解决并发问题的小技巧
    Linq实现下拉框绑定
    No DataType in DataTemplate in Windows Phone(二)
    使用TOAD操作oracle初步
    使用log4net记录server Log
    尘世一场烟火
    No DataType in DataTemplate in Windows Phone(—)
    MVC设置初始页时发生的无法找到资源的简单错误
    oracle 使用in的灵异事件
  • 原文地址:https://www.cnblogs.com/qiangupc/p/4171519.html
Copyright © 2011-2022 走看看