#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Date : 2021/5/26
# @Name : ZhouZongXin
"""
在一个文件中不间断写下如下内容
1. 2020-01-01 14:15:16
2. 2020-01-01 14:15:18
3. 2020-01-01 14:15:20
要求:
每个时间占一行,每隔2秒写入一行
当程序终止以后下次启动要求需要衔接继续写
每写一行都要在文件中显示
"""
import os
import time
PAth = os.path.dirname(__file__)
file = os.path.join(PAth, "test01.txt")
def log():
f = open(file, 'a+', buffering=1) # buffering=1行缓冲,遇到换行缓冲
count = 1
# 0:表示文件开头
# 1:表示当前位置
# 2:表示文件末尾
f.seek(0, 0) # 设置偏移量位置(从开始向前移动0个字节)
for _ in f: # 因为要有序号衔接记录,所以需要遍历原log内有多少行文件,在用count序号+=1。
count += 1 # 当遍历结束后就是最新的log行数,此时在走下方的while循环读写
while True:
print(f.readline())
data = time.strftime(f'{count}. %Y-%m-%d %H:%M:%S\n', time.localtime())
f.write(data)
time.sleep(2)
count += 1 # 每写一行统计+1次,作为下次编写的序号
log()
python--文件处理-实现实时log记录
最新推荐文章于 2023-01-02 18:26:13 发布