python删除x天前文件及文件夹

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os, time, sys, shutil

def delFiles(beforeSec, dirpath):
    for i in os.listdir(dirpath):
        filepath = "%s%s%s" %(dirpath, os.sep, i)
        if os.path.getmtime(filepath) < beforeSec:
            try:
                if os.path.isfile(filepath):
                    os.remove(filepath)
                else:
                    shutil.rmtree(filepath)

            except Exception as e:
                print(e)

if __name__ == '__main__':
    dir_path = "D:\\website\\image.xx.com\\Contracts"
    beforeDay = 10
    beforeSec = time.time() - 3600 * 24 * beforeDay
    delFiles(beforeSec, dir_path)

 

posted on 2017-10-18 21:29  林肯公园  阅读(550)  评论(0编辑  收藏  举报

导航