简体   繁体   English

如何使用python脚本删除日志前6个月

[英]How to remove 6 month before logs using python script

I have Logs_26052021.tar.xz Description: 26052021--> date: 26, month: 05, year: 2021我有Logs_26052021.tar.xz描述: 26052021--> date: 26, month: 05, year: 2021

And want to permanently remove this kind of files from location using python script.并希望使用 python 脚本从位置永久删除此类文件。 its on Unix server, version: Linux localhost 3.10.0-1160.21.1.el7.x86_64它在 Unix 服务器上,版本: Linux localhost 3.10.0-1160.21.1.el7.x86_64

what should I do.我应该怎么办。

Thanks In Advance提前致谢

using proper separation into methods.使用适当的分离方法。 Tested on python 3.9.6在 python 3.9.6 上测试

import os
from datetime import datetime


def get_files_from_path(path: str) -> list:
    result = []
    for subdir, dirs, files in os.walk(path):
        for filename in files:
            filepath = subdir + os.sep + filename
            if filename.startswith('Logs_') and filename.endswith('.tar.xz'):
                result.append(filepath)
    return result    


def get_old_files(filelist: list, max_days=184) -> list:
    currentdate = datetime.now()
    result = []
    for file in filelist:
        datestr = file.split('Logs_')[1].split('.tar.xz')[0]
        filedate = datetime.strptime(datestr, '%d%m%Y')
        tdelta = currentdate - filedate
        if tdelta.days > max_days:
            result.append(file)
    return result


def delete_files(filelist: list):
    for file in filelist:
        os.remove(file)


logfiles = get_files_from_path('testing')
oldfiles = get_old_files(logfiles)

delete_files(oldfiles)

related documentation:相关文档:

  1. Iterate over files 迭代文件
  2. strptime behavior 时间行为
  3. timedelta for substraction of dates 用于减去日期的 timedelta
  4. File deletion文件删除

Found Answer,找到答案,

find /path/Logs/ -name "*.log.*" -type f -mtime +180

But while executing this command getting SyntaxError: invalid syntax for "*.log.*"但是在执行这个命令时得到SyntaxError: invalid syntax for "*.log.*"

How should I execute this one using python ?我应该如何使用 python 执行这个?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM