6个实用的 Python 自动化脚本,你学会了吗?( 二 )


import os import threading import timedef get_file_list(file_path): #文件按最后修改时间排序dir_list = os.listdir(file_path)if not dir_list:returnelse:dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))return dir_listdef get_size(file_path):"""[summary]Args:file_path ([type]): [目录]Returns:[type]: 返回目录大小,MB"""totalsize=0for filename in os.listdir(file_path):totalsize=totalsize+os.path.getsize(os.path.join(file_path, filename))#print(totalsize / 1024 / 1024)return totalsize / 1024 / 1024def detect_file_size(file_path, size_Max, size_Del):"""[summary]Args:file_path ([type]): [文件目录]size_Max ([type]): [文件夹最大大小]size_Del ([type]): [超过size_Max时要删除的大小]"""print(get_size(file_path))if get_size(file_path) > size_Max:fileList = get_file_list(file_path)for i in range(len(fileList)):if get_size(file_path) > (size_Max - size_Del):print ("del :%d %s" % (i + 1, fileList[i]))#os.remove(file_path + fileList[i])def detectFileSize():#检测线程,每个5秒检测一次while True:print('======detect============')detect_file_size("/Users/aaron/Downloads/", 100, 30)time.sleep(5)if __name__ == "__main__":#创建检测线程detect_thread = threading.Thread(target = detectFileSize)detect_thread.start() 原文链接:
https://www.tuicool.com/articles/EnYzmuE

【6个实用的 Python 自动化脚本,你学会了吗?】


推荐阅读