Writing data in text file

Hi,
I would like to write data in text file but I get some error. The code is working and plotting the data in real time but I am not sure how to write in the text file.

import random
from itertools import count
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation 

plt.style.use('fivethirtyeight')

x_vals = []
y_vals = []

index = count ()

def animate(i):
    x_vals.append(next(index))
    y_vals.append(random.randint(0,5))
    plt.plot(x_vals, y_vals)
    plt.cla()
        
ani = FuncAnimation(plt.gcf(), animate, interval=1000)
f = open('readme.txt', 'a')
f.write(str(x_vals) + str(y_vals))
    
plt.plot(x_vals, y_vals)
plt.title('Plotting Real Time Data', fontweight ="bold")
plt.tight_layout()
plt.show()

Hi Engr,

You wrote:

“I would like to write data in text file but I get some error.”

Is the error a secret? Do you want us to guess what it might be?

Please copy and paste the full traceback, starting with the line
“Traceback…” to the end of the error message.

Thank you.

Hi, the plot does not update with animation and there is no data appear in the text file. It just stuck with figure open and no data appear in the figure and nothing written in the text file. I don’t see any error message printed in the shell.

I’m pretty sure you will find what you need in the matplotlib documentation. They’ve also got a lot of good animation examples:

https://matplotlib.org/stable/gallery/index.html#animation