Code Review
ad
adsquaired at gmail.com
Tue May 24 16:10:37 EDT 2011
Hello all,
Please review the code pasted below. I am wondering what other ways
there are of performing the same tasks. This was typed using version
3.2. The script is designed to clean up a directory (FTP, Logs, etc.)
Basically you pass two arguments. The first argument is an number of
days old to delete. The second argument is the directory where the
files and folders should be deleted. I imagine one enhancement would
be to create a function out of some of this.
### BEGIN ###
import os
import time
import shutil
import argparse
CurrentTime = time.time()
epocDay = 86400 # seconds
parser = argparse.ArgumentParser(description = "Delete files and
folders in a directory N days old", add_help=False,
prog='directorycleaner', usage='%(prog)s 7 c:\\temp')
parser.add_argument('days', type=int, help="Numeric value: delete
files and folders older then N days")
parser.add_argument('directory', help="delete files and folders in
this directory")
parser.print_help()
args = parser.parse_args()
dictKeys = (vars(args))
HowManyDays = dictKeys['days']
WhatDirectory = dictKeys['directory']
print (HowManyDays)
print (WhatDirectory)
DaysToDelete = HowManyDays * epocDay
dirExists = os.path.exists(WhatDirectory)
if dirExists == False: print ("The directory is missing")
DirListing = os.listdir(WhatDirectory)
for files in DirListing:
# Get the absolute path of the file name
abspath = (os.path.join(WhatDirectory, files))
# Get the current creation time of the file in epoc format
(midnight 1/1/1970)
FileCreationTime = (os.path.getctime(abspath))
# time.ctime converts epoch to a normal date
#print (time.ctime(CurrentTime))
# Get the date from seven days ago
WeekOldFileDate = CurrentTime - DaysToDelete
#print (CurrentTime)
#print (FileCreationTime)
#print (WeekOldFileDate)
#If the file is older than seve days doe something
if FileCreationTime < WeekOldFileDate:
#check if the object is a file
if os.path.isfile(abspath): os.remove(abspath)
# It is not a file it is a directory
elif os.path.isdir(abspath): shutil.rmtree(abspath)
##### END ####
More information about the Python-list
mailing list