根据正则表达式来清理文件夹

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()
复制代码
原文地址:https://www.cnblogs.com/qiangupc/p/4171519.html