python 每日日志的记录与删除

current_time_logo = datetime.datetime.now().strftime('%Y-%m-%d')

def write_data(data):
global current_time_logo
with open('./log/trace_request.log', 'a+') as logs:
current_time = datetime.datetime.now().strftime('%Y-%m-%d')
if current_time != current_time_logo:
current_time_logo = current_time
       # 记录从头开始算起
logs.seek(0)
       # 删除全部内容
logs.truncate()
logs.write(str(data) + "\n")
else:
logs.write(str(data) + "\n")

Python 文件 truncate() 方法用于截断文件并返回截断的字节长度。

指定长度的话,就从文件的开头开始截断指定长度,其余内容删除;不指定长度的话,就从文件开头开始截断到当前位置,其余内容删除

truncate() 方法语法如下:

fileObject.truncate([size])

转载于:https://www.cnblogs.com/love-chen-forever/p/11120572.html