Python : 打印 While Loop 数据集到一个文件

Python : Printing While Loop data set to a file

我正在尝试获取传感器数据并通过 JSON 将其绘制成图表。 我想读取前 100 个传感器值并创建一个文件,在第 100 个之后,我想用 101 替换第一个,用 102 替换第二个......等等,所以文件不断显示最新的 100 行。

假设我有一个随机数据流每 3 秒进入标准输出,例如这样..

from random import randint
import time

def loop():
        print(randint(100,200))

while True:
        loop()
        time.sleep(3)

如何捕获 100 行输出,并将这些数据写入文件?

理想情况下,每次 ping 操作都应将文件替换为新数据。 感谢您的帮助!

一个可行的粗略解决方案:

from random import randint
import time

def loop():
    return randint(100,200)

def save_lst(lst):
    with open("mon_fich", "w") as f:
        f.write(", ".join(lst))

lst = list()
while True:
        lst.append(str(loop()))
        if len(lst)>=100:
            save_lst(lst)
            lst = list()
        time.sleep(0.001)

如何保留一个计数器变量,并在每次达到 100(模 100)时将其重置为 0。此变量可用作写入文件的索引:

i = 0
while True:
    write_file(i, loop(), filename)
    i += 1
    i = i % 100    

def write_file(line, input, filename):
    with open(filename, 'r') as f:
        lines = f.readlines()
    lines[line] = input   # <=== Replace the nth line with current input 
    with open(filename, 'w') as f:
        f.writelines(lines)
    out.close()