Differences

This shows you the differences between two versions of the page.

Link to this comparison view

pydeleteoldfiles [2014/10/26 01:52] (current)
Line 1: Line 1:
 +==== Python example to delete old files ====
 +<code python>
 +#!python
  
 +# get file date / time info
 +
 +import os, sys, time
 +import logging
 +import logging.config
 +import ConfigParser
 +
 +__logConfigFile = '​py_logging.conf'​
 +__log_name = '​pylog.log'​
 +__MAX_LOG_FILE_SIZE = 100 * 1000
 +__confFile = '​path.conf'​
 +__enableDelete = False
 +
 +def checkLogFileSize(logFileName):​
 + fileSize = 0
 + try:
 + fileSize = os.path.getsize(logFileName)
 + except:
 +     print(__log_name + " not found or could not delete"​)
 +
 + if fileSize > __MAX_LOG_FILE_SIZE:​
 + try:
 + if os.path.isfile(logFileName+'​.1'​):​
 + os.remove(logFileName+"​.1"​)
 + os.rename(logFileName,​ logFileName+'​.1'​)
 + except OSError,​inst:​
 + print "​OSError:"​+str(inst)
 +
 +def walkTree(top,​ callback):
 +    '''​recursively descend the directory tree rooted at top,
 +       ​calling the callback function for each regular file'''​
 +
 +    for root, dirs, files in os.walk(top):​
 +        pathname = os.path.join(root,​ f)
 +        callback(pathname)
 +
 +def visitFile(file):​
 + ct,​at,​mt=os.path.getctime(file),​ os.path.getatime(file),​ os.path.getmtime(file)
 + ctd = int(time.time())-ct
 + ctDays = ctd / (3600*24)
 + # print "​__enableDelete:​ "​+__enableDelete+"​ "​+str(type(__enableDelete))
 + if __enableDelete:​
 + if ctDays >= 1:
 + __logger.debug("​delete file : " +file)
 + try:
 + os.remove(file)
 + except:
 + __logger.error(file+"​ unable to delete"​)
 + pass
 +
 +if __name__ == "​__main__":​
 + cp = ConfigParser.ConfigParser()
 + mm = cp.read([__confFile])
 + visitPath = cp.get('​DEFAULT','​path'​)
 + __enableDelete = cp.get('​DEFAULT','​enableDelete'​)
 +
 + #  remember to update __log_name - this should be same name as defined in 
 + checkLogFileSize(__log_name)
 +
 + logging.config.fileConfig(__logConfigFile)
 + __logger = logging.getLogger('​mylog'​)
 + __logger.debug("​Path:​ " +visitPath)
 + __logger.debug("​enableDelete:​ "​+__enableDelete)
 +
 +walkTree(visitPath,​visitFile)
 +</​code>​
 +
 +----
 +  * [[pythoninfo|Back to Python]]
pydeleteoldfiles.txt ยท Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0