首页 > 代码库 > 根据正则表达式来清理文件夹
根据正则表达式来清理文件夹
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:]
else: return 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()
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:]
else: return 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()
根据正则表达式来清理文件夹
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。