用Python实现-自动清理超过3天的文件及文件夹

# -*- coding: utf-8 -*-
"""
Created on Tue Aug 16 16:02:49 2022
Todo: Regularly delete user files for more than 3 days.
@author: zq.hou
"""

import os
import time


def delete_file(dpath, dt):  # path是路径,t是文件保存时间(单位:s)
    files = os.listdir(dpath)  # 获取文件夹下所有文件和文件夹
    for file in files:
        filepath = os.path.join(dpath, file)
        if os.path.isfile(filepath):  # 判断是否是文件
            last = int(os.stat(filepath).st_mtime)  # 最后一次访问的时间
            now = int(time.time())  # 当前时间
            if now - last >= dt:
                os.remove(filepath)  # 删除过期文件
                print(filepath + "was removed!")
        elif os.path.isdir(filepath):  # 如果是文件夹,则继续遍历
            delete_file(filepath, dt)
            if not os.listdir(filepath):  # 如果是空文件夹,则删除
                os.rmdir(filepath)
                print(filepath + "was removed!")


if __name__ == '__main__':
    path = "/home/admin/zeqing/web/users"  # 用户文件保存目录
    t = 3*24*60*60  # 文件保存3天时间
    ts = 60*60  # 每隔1小时清理一次
    while True:
        delete_file(path, t)
        time.sleep(ts)


版权声明:本文为TwinkleSStar原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。