python删除N天前文件

发布时间:2019-08-27 08:03:04编辑:auto阅读(1726)

    #/usr/bin/env python
    # -*- coding:utf-8 -*-
    #Author='Jun'
    import os
    import sys
    import time
    
    def removefiles(beftime, defalutpath='.'):
        for i in os.listdir(path):
            filename = path + os.sep + i
            if os.path.getmtime(filename) < beftime:
                try:
                    if os.path.isfile(filename):
                        os.remove(filename)
                    elif os.path.isdir(filename):
                        os.removedirs(filename)
                    else:
                        os.remove(filename)
                    print "%s remove success." % filename
                except Exception as error:
                    print error
                    print "%s remove faild." % filename
    
    if __name__ == "__main__":
        try:
            path = sys.argv[1]
            breday = int(sys.argv[2])
            bretime = time.time() - 3600 * 24 * breday
            removefiles(bretime, path)
        except Exception as e:
            print e
            sys.exit(-1)


关键字