[Python] 删除指定目录下后缀为 xxx 的过期文件

import os
import time
import datetime


def should_remove(path, pattern, days):
    if not path.endswith(pattern):
        return False

    mtime = os.path.getmtime(path)
    now = time.time()
    result = now - mtime > days * 24 * 3600

    print "
>>>>>>>>>>>>>>
"
    print "file:         ", path
    print "mtime:        ", datetime.datetime.fromtimestamp(mtime)
    print "now:          ", datetime.datetime.fromtimestamp(now)
    print "> %d days:    " % days, result

    return result


def findNremove(path, pattern, days):
    print "path:    ", path
    print "pattern: ", pattern
    print "days:    ", days

    for r, d, f in os.walk(path):
        for files in f:
            file_path = os.path.join(r, files)
            if should_remove(file_path, pattern, days):
                try:
                    print "Removing       %s" % (file_path)
                    #os.remove(file_path)
                except Exception, e:
                    print e
                else:
                    print "removed        %s" % (file_path)


if __name__ == '__main__':
    path = os.path.join("/home", "bshao", "projects", "driver_client", "tmp")
    days = 10
    pattern = ".apk"
    findNremove(path, pattern, days)

原文地址:https://www.cnblogs.com/shaobin0604/p/6083635.html