Python traverses files in a folder and deletes them according to the required time

Traverse the files in the folder under the specified path, and set the corresponding time to delete the file based on the comparison between the file generation time and the existing time.

import os  
import datetime
import shutil

def gci(base):
    #base = 'C:\\robotframework\\logs'
    #output_dir = os.path.join(base, 'logs', datetime.datetime.now().strftime('%Y%m%d'),datetime.datetime.now().strftime('%H-%M-%S'))
    listdir = os.listdir(base)
    #print listdir
    
    
    now = datetime.datetime.now()
    #minutes\hours
    delta = datetime.timedelta(hours=1) 
    for i in range(len(listdir)):  
        dir = os.path.join(base,listdir[i])
        #print dir    
        dir1 = os.listdir(dir)
        #print dir1
        for j in range(len(dir1)):
            dir2 =dir1[j]
            #print dir2
            dir3 = os.path.join(dir,dir2)
            #print dir3        
            #dir2 = os.path.join(dir,dir1[j])
            #print dir2
            #dir3 = os.listdir(dir2)
            #print dir3
            #ctime= datetime.datetime.fromtimestamp(os.path.getctime(os.path.join(dir,dir2)))
            ctime= datetime.datetime.fromtimestamp(os.path.getctime(dir3))
            print ctime
            
            if ctime < (now - delta):
                shutil.rmtree(dir3)
            else:
                print dir3 + ': is not needed to be removed!'
                #os.chdir(dir)
                #shutil.rmtree(dir2) 
#递归遍历base目录下所有文件
gci('C:\\robotframework\\logs')   

 

Guess you like

Origin blog.csdn.net/tjfsuxyy/article/details/87916038