os模块练习题

1、写一个删除日志的脚本,把三天前的日志并且为空的日志删除

 

我写的

import os,time
def ces(ces):
time_tuple = time.strptime(ces, '%Y-%m-%d')
time_stamp_nwo = time.mktime(time_tuple)
return time_stamp_nwo

#三天前的
for cur_path,dirs,files in os.walk(r'C:Usersv-dongchunguangPycharmProjectsuntitledday5logs'):
seven = int(time.time()) - 60 * 60 * 24 * 3
for file in files:
files=file.split('_')[1].split('.')[0]
c=ces(files)
cc=os.path.join(cur_path,file)#拼接路径
ccs=os.path.abspath(cc)#不加找不到
if c<seven or os.path.getsize(cc)==0:
if time.strftime('%Y-%m-%d') in file:#如果当天文件在这里就不删除
continue
os.remove(cc)

标准的
import os
import time

day = 60 * 60 * 24 * 3

def str_to_timestamp(str_time,format='%Y-%m-%d'):
time_tuple = time.strptime(str_time,format)
return int(time.mktime(time_tuple))


def clean_log(path):
if os.path.isdir(path):
for cur_path,dirs,files in os.walk(path):
for file in files:
if file.endswith('.log'):

#apache_2020-09-04.log
#a.log
try:
file_time = file.split('.')[0].split('_')[-1]
except Exception as e:
print(e)
print('%s 不是标准的日志文件,不处理'%file)
else:
pass
file_time_stamp = str_to_timestamp(file_time)
ago_time_stamp = time.time() - day
file_abs_path = os.path.join(cur_path, file)
if file_time_stamp < ago_time_stamp or os.path.getsize(file_abs_path) == 0 :
# if time.strftime('%Y-%m-%d') in file:
# continue
os.remove(file_abs_path)
else:
print('路径错误!')


clean_log('logs')

原文地址:https://www.cnblogs.com/weilemeizi/p/14524470.html