如何将每一行分别写入并保存在一个txt文件中?

How to write and save each line separately on a txt file?

我正在 运行宁两个 .py 文件。创建一个介于 1 和 10 之间的随机浮点数,然后将其写入文件。 另一个正在绘制这些数字。我的动画在我编写和 "save" 时工作正常,但随着编写过程的自动化,数据仅在我停止程序时保存,并且 file.close() 采取行动(在我的循环之外)。

我试过将 .open 和 .close() 放在循环中,但这样它只保存了我写的最后一行,我仍然需要暂停程序。

作者代码:

import random
import time


i=0
with open('datatest.txt', 'w') as a:
    while True:
        line = str(i) + ',' + str(random.uniform(1,10)) + '\n'
        a.write(line)
        print(line)
        i += 1
        time.sleep(9)

图形动画代码:

#!/usr/bin/env python
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np


fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    print("inside animate")
    pullData = open("data.txt","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []

    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            xar.append(float(x))
            yar.append(float(y))

    ax1.clear()
    ax1.plot(xar,yar)

    plt.xlabel('Hora')
    plt.ylabel('Valor Dado')
    plt.title('Pseudo-Sensor x Hora')


ani = animation.FuncAnimation(fig, animate, interval=1000) 
plt.show()

我原本希望查看 'live action' 保存在我的 txt 文件中的写作过程,因此我的图表会随着每个保存步骤 运行.

刷新

感谢您的宝贵时间!

每次都可以以追加模式打开文件

while True:    
    with open('datatest.txt', 'a+') as a:
        line = str(i) + ',' + str(random.uniform(1,10)) + '\n'
        a.write(line)
        print(line)
        i += 1
        time.sleep(9)