Delete files that are older than 7 days

后端 未结 3 579
慢半拍i
慢半拍i 2021-01-05 11:04

I have seen some posts to delete all the files (not folders) in a specific folder, but I simply don\'t understand them.

I need to use a UNC path and delete all the f

3条回答
  •  长情又很酷
    2021-01-05 11:54

    Based in Vadim solution a more flexible approach Remember os.unlink(fileWithPath) removes everything in that folder older than X days, so be careful.

    ############ DELETE OLDER THAN X ############
    current_time = time.time()
    daysToDelete = 7
    directory = '/absolute/path/to/folder/'
    
    for dirpath,_,filenames in os.walk(directory):
        for f in filenames:
            fileWithPath = os.path.abspath(os.path.join(dirpath, f))
            creation_time = os.path.getctime(fileWithPath)
            print("file available:",fileWithPath)
            if (current_time - creation_time) // (24 * 3600) >= daysToDelete:
                os.unlink(fileWithPath)
                print('{} removed'.format(fileWithPath))
                print("\n")
            else:
                print('{} not removed'.format(fileWithPath))
    

提交回复
热议问题