删除目录下指定日期前的所有文件

时间:2022-11-12 12:06:50
# -*- coding: utf-8 -*-

import shutil, os
import time,datetime

timeDateStr="2018-01-01 00:00:00"   #delete module's dead line
time1=datetime.datetime.strptime(timeDateStr,"%Y-%m-%d %H:%M:%S")
secondsFrom1970=time.mktime(time1.timetuple())


def remove_oldFile(path, deadline):
    print(path)
    if (not os.path.exists(path)):
        return 1
    os.chdir(path)
    ds = list(os.listdir())
    if not ds:
        return 2
    for d in ds:
        fileOrDir = os.path.join(path, d) 
        if os.path.isfile(fileOrDir):
            if (os.path.getmtime(fileOrDir) - secondsFrom1970 < 0):                
                print("remove file:",d)
                os.remove(fileOrDir)
        elif os.path.isdir(fileOrDir):   
            remove_oldFile(fileOrDir,deadline)


remove_oldFile(r'C:\Users\Administrator\Desktop\bin', secondsFrom1970)