Python : Printing While Loop data set to a file
Question: I am trying to take sensor data and plot it into a graph via JSON. I would
like to read the first 100 sensor values and create a file, after the 100, I
want to replace the 1st with 101, 2nd with 102... etc so the file is
constantly showing the latest 100 lines.

Say I have a random data stream coming in every 3 seconds to the standard
output such as this..

    
    
    from random import randint
    import time
    
    def loop():
            print(randint(100,200))
    
    while True:
            loop()
            time.sleep(3)
    

How do I capture say 100 lines of the output, and write this data to a file?

Ideally the file should be replaced every ping by the new data. Thank you for
your help!


Answer: A working crude solution :

    
    
    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)
    

