python实现删除Linux服务器上同路径下不同目录中不同日期目录下10天前的文件
同路径目录:/home/llj/www/
同路径目录下不同目录有:"SubscriptionARES/","SubscriptionCNES/","SubscriptionCRES/","SubscriptionINES/"
同路径目录下不同目录中不同日期目录有:"202107","202108"
目录结构如下图:

具体代码如下:
import os
import time
import subprocess
dir_first="/home/llj/www/"
dir_two=["SubscriptionARES/","SubscriptionCNES/","SubscriptionCRES/","SubscriptionINES/"]
#获取当前月份
current_month=time.strftime("%Y%m")
print(current_month,type(current_month))
def subprocess_Popne(cmd_args):
obj=subprocess.Popen(cmd_args,shell=True,universal_newlines=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result=obj.stdout.read().split("\n")[0]
return result
#获取上个月份
last_month_cmd="date -d '-1month' +%Y%m"
last_month_result=subprocess_Popne(last_month_cmd)
def execute_cmd(month_dir,cmd_res,current_month_number=current_month):
#如果当前日期目录中文件个数大于0,该目录中有文件存在,则执行查找删除10天前被更改过的文件
if int(cmd_res) > 0:
res = subprocess.call(f"find {month_dir} -type f -name '*.zip' -mtime +10 | xargs rm -f",shell=True)
if res == 0:
print(f"删除{month_dir}目录中前10天文件成功!")
#如果当前日期目录中文件个数为0,该目录中文件不存在
else:
#分割获取目录中当前日期
c_m_n=month_dir.split("/")[5]
if int(c_m_n) < int(current_month_number): #获取当前条件中月份目录小于当月目录
os.removedirs(month_dir)
print(f"该{month_dir}目录下不存在文件,会被删除掉!")
#上个月日期目录被删除了不存在了,进入当月日期目录下
if not os.path.exists(month_dir):
current_month_dir_date_path = os.path.join(d1,current_month)
# 判断当前月份日期目录是否存在
if not os.path.exists(current_month_dir_date_path):
return
#当前月份日期目录存在
cmd_result = subprocess_Popne(f"find {current_month_dir_date_path} -type f -name '*.zip'| wc -l")
if int(cmd_result) == 0:
return
else:
res = subprocess.call(f"find {current_month_dir_date_path} -type f -name '*.zip' -mtime +10 | xargs rm -f", shell=True)
if res == 0:
print(f"删除{current_month_dir_date_path}目录中前10天文件成功!")
else:#获取当前条件中月份目录不小于当月目录
return
dir_path=[]
#判断第一层目录是否存在
if os.path.isdir(dir_first):
for d in dir_two:
#第一层目录存在,则拼接第二层目录
f_d=os.path.join(dir_first,d) #拼接为/home/llj/www/SubscriptionARES/
#拼接完成的目录路径添加到空列表中
dir_path.append(f_d)
#for循环拼接完成的列表
for d1 in dir_path:
# 拼接/home/llj/www/SubscriptionARES/目录加上个月份日期进行判断 #/home/llj/www/SubscriptionARES/202107
last_month_dir_date_path = os.path.join(d1,last_month_result)
# 判断是否存在上个月份日期目录 #/home/llj/www/SubscriptionARES/202107
if not os.path.exists(last_month_dir_date_path):
# 上个月日期目录不存在则拼接当前月份日期目录
#拼接/home/llj/www/SubscriptionARES/目录加上当月份日期进行判断#/home/llj/www/SubscriptionARES/202108
current_month_dir_date_path = os.path.join(d1,current_month)
# 判断当前日期目录是否存在
if not os.path.exists(current_month_dir_date_path):
continue #这快要加continue,不然会执行下面的代码
#当前日期目录存在
#查找当前日期目录中文件的个数
cmd_result = subprocess_Popne(f"find {current_month_dir_date_path} -type f -name '*.zip'| wc -l")
execute_cmd(current_month_dir_date_path,cmd_result)
continue #这快要加continue,不然会执行下面的代码
#有上个月份日期目录存在
cmd_result = subprocess_Popne(f"find {last_month_dir_date_path} -type f -name '*.zip'| wc -l")
execute_cmd(last_month_dir_date_path,cmd_result)

浙公网安备 33010602011771号