This article mainly introduces the folder cleanup program implemented by python, which can be cleaned up by time and specified configuration files. if you need it, refer to the following:
The code is as follows:
Foldercleanup. py-d 10-k c: \ test \ keepfile.txt c: \ test
Only the subfolders specified in keepfile.txt and subfolders of the nearest 10 days are reserved for the c: \ testdirectory.
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 are created in recent % 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 (day 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 t:
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, day) 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])