Return to Snippet

Revision: 61471
at December 15, 2012 02:28 by djmornyc


Updated Code
#!/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()

Revision: 61470
at December 15, 2012 02:15 by djmornyc


Initial Code
#!/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):
      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()

Initial URL

                                

Initial Description
*Does not check permissions.
python cleanFiles.py --directory=/home/win98/tmp/ --ageInDays=2

Initial Title
Clean files/directory by time.

Initial Tags
python, script

Initial Language
Python