删除日志文件中超过 10 天的所有行

我有一个文件夹,我正在尝试删除所有超过 10 天的行。


输入如下:error.log


20200122024227-vision.log

20200122024730-vision 20200122024930 Missing 20200122024730-vision.log

20200520210139 Failed :

20200811152053-ibm 20200811152254 Missing

20200812164636-ibm_global 20200812164837 Missing

20200812210311-ibm_global 20200812210512 Missing

20200813080856-ivr 20200813081056 Missing

20200813092556-chat_global 20200813092757 Missing

20200813125528-ibm_global 20200813125728 Missing

20200813163610-acaps_global 20200813163810 Missing

20200813172428-mvs_global 20200813172629 Missing

20200820204216-pos_global 20200820204417 Missing

20200910103742-chatbot_global 20200826103943 Missing

20200913103742-chatbot_global 20200826103943 Missing

20200914103742-chatbot_global 20200826103943 Missing

20200915103742-chatbot_global 20200826103943 Missing

20200916103742-chatbot_global 20200826103943 Missing

我的输出应该是:


20200910103742-chatbot_global 20200826103943 Missing

20200913103742-chatbot_global 20200826103943 Missing

20200914103742-chatbot_global 20200826103943 Missing

20200915103742-chatbot_global 20200826103943 Missing

20200916103742-chatbot_global 20200826103943 Missing

这些日志不到 10 天。


首先,我需要从 is 行获取时间戳20200916103742,并检查它是否小于保留期。如果它被保留,我们必须保留,否则删除。我传递给程序的参数是当前时间戳,保留期为 10 天。


所以这意味着我只需要最近 10 天的日志,然后从 error.log 中删除


代码如下:


current_date = sys.argv[1]

retention_period  = sys.argv[2]

old_date = int(current_date ) - int(redention_period*1000000)

path = "abc/log/log_test/"


error_file = path+"error.log"


file = open(error_file)

output = []


for line in file:

    print(line)

    str_log_key = line[0:13]

    log_key = int(str_log_key)


    if log_key in range(old_date, current_date):

        output.append(line)


f.close()

f = open(error_file, 'w')

f.writelines(output)

f.close()

我收到如下错误:


if log_key in range(old_date, current_date):

  TypeError: 'str' object cannot be interpreted as an integer

还有其他更好的编码方式吗?


当年话下
浏览 145回答 3
3回答

哆啦的时光机

这个功能可能会帮助你:from datetime import date, timedeltadef del_old():    limit = "".join(str(date.today() - timedelta(days = 10)).split("-"))    with open("error.log", "r") as file:         data = file.readlines()    with open("error.log", "w") as file2:         for line in data:             (int(line.lstrip()[:8]) > int(limit)) and file2.write(line)

料青山看我应如是

假设present_date您的意思是current_date那么您也需要将其转换为整数。

holdtom

另一种方法是创建一个新文件:from datetime import dateerrorfile = open(f'error.log', 'r')errorNew = open(f'error_new.log', 'a+')current_date = date.today()for line in errorfile:&nbsp; &nbsp; date_line = date(int(line[0:4]), int(line[4:6]), int(line[6:8]))&nbsp; &nbsp; diff = (current_date - date_line)&nbsp; &nbsp; if diff.days < 10:&nbsp; &nbsp; &nbsp; &nbsp; errorNew.write(line)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python