/ Published in: Python
*Does not check permissions.
python cleanFiles.py --directory=/home/win98/tmp/ --ageInDays=2
python cleanFiles.py --directory=/home/win98/tmp/ --ageInDays=2
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/usr/bin/env python import argparse import os import sys from time import strptime, time def parse_arguments(args): argParse = argparse.ArgumentParser( \ description='Deletes file in a directory older than a period in days') argParse.add_argument('--directory' \ , help = 'Target directory' , required = True , type = check_directory) argParse.add_argument('--ageInDays' \ , help = 'Integer age in days' , required = True , type = int) return argParse.parse_args() def unlink_files_by_days(targetDirectory, ageInDays): for checkFile in os.listdir(targetDirectory): filePath = os.path.join(targetDirectory, checkFile) fileAgeInDays = get_file_age_in_days(filePath) if (fileAgeInDays >= ageInDays and os.path.isfile(filePath)==True): print 'Deleting {0} {1}'.format(filePath, fileAgeInDays) os.unlink(filePath) def get_file_age_in_days(filePath): return (time() - os.stat(filePath).st_mtime)/86400 def check_directory(checkDirectory): if os.path.isdir(checkDirectory): return checkDirectory print 'Invalid directory {0}'.format(checkDirectory) exit() def main(): validArgs = parse_arguments(sys.argv) unlink_files_by_days(validArgs.directory, validArgs.ageInDays) if __name__=='__main__': main()