python腳本自動刪除老文件


#!/usr/bin/env python2
#-*- coding:UTF-8 -*-
import subprocess
import os
import datetime

#python獲取磁盤信息

#磁盤最大使用閾值
max_size = 20
abs_path="/root"
temp_str="test"

#定義刪除日志文件
del_log = "del_log.txt"

#檢查是否要刪除文件
def is_del():
	exec_info = subprocess.check_output("df -h /",shell=True)
	disk_info = exec_info.split(' ')[-2].split('%')[0]
	#獲取指定目錄文件信息,並排序
	files = sorted([item for item in os.listdir(abs_path) if item.startswith(temp_str)])
	if int(disk_info) > int(max_size):
		if len(files)>0:
			del_name(os.path.join(abs_path,files[0]))
	else:
		return 0

#寫日志文件裝飾器
def write_log(func):
	def wrapper(file):
		del_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
		context = "{} {} 文件已刪除 ---->by python\n".format(del_time,file)
		with open(os.path.join(abs_path,del_log),"a+") as f:
			f.writelines(context)
		print file
		return func(file)
	return wrapper
#執行刪除老文件命令
@write_log
def del_name(file):
	#刪除指定文件
	os.remove(file)

def main():
	is_del()


if __name__ == '__main__':
	main()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM