Share the folder cleanup program implemented by python,

Source: Internet
Author: User

Share the folder cleanup program implemented by python,

Usage:
Copy codeThe 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:
Copy codeThe 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:

Copy codeThe 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])

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.