代码改变世界

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

2016-11-20 21:43  shaobin0604  阅读(860)  评论(0编辑  收藏  举报
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 "\n>>>>>>>>>>>>>>\n"
    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)