3 回答

TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
這個(gè)功能可能會(huì)幫助你:
from datetime import date, timedelta
def 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)

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
假設(shè)present_date
您的意思是current_date
那么您也需要將其轉(zhuǎn)換為整數(shù)。

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
另一種方法是創(chuàng)建一個(gè)新文件:
from datetime import date
errorfile = open(f'error.log', 'r')
errorNew = open(f'error_new.log', 'a+')
current_date = date.today()
for line in errorfile:
date_line = date(int(line[0:4]), int(line[4:6]), int(line[6:8]))
diff = (current_date - date_line)
if diff.days < 10:
errorNew.write(line)
添加回答
舉報(bào)