清除指定目录下的子文件, 只保留与给定的正则表达式匹配且最后创建的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()
完!