Use:
The code is as follows:
foldercleanup.py-d 10-k c:\test\keepfile.txt C:\Test
Indicates that the C:\Test directory retains only the last 10 days of subfolders and subfolders specified in Keepfile.txt.
Code:
The code is as follows:
Import OS
Import Os.path
Import datetime
Def getOption ():
From Optparse import Optionparser
Des = "Clean up the folder with some options"
Prog = "Foldercleanup"
ver = "%prog 0.0.1"
Usage = "%prog [options] foldername"
p = Optionparser (Description=des, Prog=prog, Version=ver, Usage=usage,add_help_option=true)
P.add_option ('-d ', '--days ', action= ' store ', type= ' string ', dest= ' days ', help= ' keep the subfolders which is created in Recent%days% days ")
P.add_option ('-K ', '--keepfile ', action= ' store ', type= ' string ', dest= ' keepfile ', help= ' keep the subfolders which are Recorded in text file%keepfile% ")
Options, arguments = P.parse_args ()
If Len (arguments)! = 1:
Print ("Error:must input one directory as only one parameter")
Return
Return options.days, Options.keepfile, Arguments[0]
def precheckdir (dir):
if (not os.path.exists (dir)):
Print ("Error:the directory your input is not existed")
Return
if (not Os.path.isdir (dir)):
Print ("error:the parameter your input is not a directory")
Return
Return Os.path.abspath (dir)
Def iskeepbyday (dir, day):
Indays = False
If (is not None):
t = os.path.getctime (dir)
Today = Datetime.date.today ()
CreateDate = Datetime.date.fromtimestamp (t)
Indate = Today-datetime.timedelta (days = Int (day))
Print (CreateDate)
if (CreateDate >= indate):
Indays = True
Print (indays)
Return indays
Def iskeepbykeepfile (dir, keepfile):
Needkeep = False
Print (dir)
If (Keepfile is not None):
Try:
KF = open (Keepfile, "R")
For f in Kf.readlines ():
Print (f)
if (Dir.upper (). EndsWith ("\ \" + F.strip (). Upper ())):
Needkeep = True
Kf.close ()
Except
Print ("Error:keep file cannot be opened")
Print (Needkeep)
Return Needkeep
Def removesubfolders (dir, Day, Keepfile):
Subdirs = Os.listdir (dir)
For SubDir in Subdirs:
SubDir = Os.path.join (Dir,subdir)
if (not Os.path.isdir (subdir)):
Continue
Print ("----------------------")
if (not Iskeepbyday (subdir) and (not Iskeepbykeepfile (SubDir, Keepfile))):
Print ("Remove subfolder:" + subdir)
Import Shutil
Shutil.rmtree (Subdir,true)
Def foldercleanup ():
(Day, Keepfile, dir) = GetOption ()
dir = Precheckdir (dir)
If Dir is None:
Return
Removesubfolders (Dir,day,keepfile)
If __name__== ' __main__ ':
Foldercleanup ()
Keep the last zip file in the directory:
The code is as follows:
def keeplastnumzips (num)
Def extracttime (f):
Return Os.path.getctime (f)
Zipfiles = [Os.path.join (Zipdir, F)
For f in Os.listdir (Zipdir)
If Os.path.splitext (f) [1] = = ". Zip"]
If Len (zipfiles) > num:
Zipfiles.sort (Key=extracttime, Reverse=true)
For I in range (num, len (zipfiles)):
Os.remove (Zipfiles[i])