python_操作文件,删除log

#2、写一个清理日志的程序,把三天前的日志删掉,
#          保留今天的、昨天和前天的。
import os
import time
def Clear_logs(N):
    file_list = get_all_file()
    for file in file_list:
        if file.endswith('.log'):
            f = os.path.split(file)[1]
            t = f[-14:-4]
            if time.time()-StrToTimestamp(t) >= 24*60*60*int(N):
                os.remove(file)
def get_all_file(path='/Users/wym/Desktop/work/Besttest/笔记/day6/day6笔记/logs'):
    file_list = []
    for cur_path, cur_dirs, cur_files in os.walk(path):
        for name in cur_files:
            file_list.append(os.path.join(cur_path,name))
    return file_list
def StrToTimestamp(Str=None,format='%Y-%m-%d'):
    #格式化好的时间转时间戳:
    if Str:
        timep = time.strptime(Str, format)
        res = time.mktime(timep)
    else:
        res = time.time()
    return int(res)
N = input('请输入需要清除几天前的日志:')
Clear_logs(N) #清除N天前的日志
原文地址:https://www.cnblogs.com/mercywym/p/10124511.html