清理旧文件的脚本
清理(Linux)本地文件,防止磁盘撑爆;此脚本经过测试没问题。
测试截图:(在有Python解释器的服务器上测试就行)

同时在清理文件的基础上添加了删除空文件夹的一个逻辑,代码很简单。
这个脚本需要配合Azkaban或者Oozie或者DS进行调度,才能达到定时清理旧文件的目的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
import os import time import sys
args = sys.argv
def delete_old_files(directory): """ 传入给定文件目录,删除该目录下时间超过7天的文件,后续会产生空文件夹 :param directory: 要进行处理的文件目录 :return: """ current_time = time.time() one_week_seconds = 7 * 24 * 60 * 60 for root, dirs, files in os.walk(directory): for file in files: file_path = os.path.join(root, file) file_stat = os.stat(file_path) print(file_stat.st_mtime)
file_age = current_time - file_stat.st_mtime if file_age > one_week_seconds: os.remove(file_path) print("已删除文件:", file_path)
def delete_empty_folders(directory): """ 删除上一个函数产生的空文件夹 :param directory: 要删除的空文件夹目录 :return: """ for root, dirs, files in os.walk(directory, topdown=False): for dir in dirs: folder_path = os.path.join(root, dir) if not os.listdir(folder_path): os.rmdir(folder_path) print("已删除空文件夹:", folder_path)
if __name__ == '__main__': directory_path = args[1] delete_old_files(directory_path) delete_empty_folders(directory_path)
|