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


    清除指定目录下的子文件, 只保留与给定的正则表达式匹配且最后创建的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 
    = '\n\
      Function:\n\
        Clean Up subfolders in (dir), as a result :\n\
        just keep the subfolders which are matched with (regrex), \n\
        and the number of the subfoler cannot more then (num).\n\
      Usage:\n\
        python %s dir regrex num\n\
      
    ' %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()

    完!

  • 相关阅读:
    设计模式
    雨夹雪背景特效
    lottie-前端实现AE动效
    响应式布局实现原理
    关于小程序(含uniapp)中使用npm模块
    使用脚手架快速搭建React项目
    vue项目接入友盟统计站点数据
    git常用命令
    uniapp请求方法的封装
    小程序获取用户登录及手机号登录
  • 原文地址:https://www.cnblogs.com/itech/p/1991756.html
Copyright © 2011-2022 走看看