【问题标题】:How to write and save each line separately on a txt file?如何在txt文件中分别写入和保存每一行?
【发布时间】:2019-05-24 19:51:08
【问题描述】:

我正在运行两个 .py 文件。创建一个介于 1 和 10 之间的随机浮点数,然后将其写入文件。 另一个正在绘制这些数字。我的动画在我编写和“保存”时运行良好,但随着编写过程的自动化,数据只有在我停止程序时才会保存,并且 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()

我希望查看保存在我的 txt 文件中的写入过程的“实时动作”,因此我的图表会随着每个保存步骤的运行而刷新。

感谢您的宝贵时间!

【问题讨论】:

    标签: python-3.x matplotlib dynamic writefile


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 这就像一个魅力。它有一点延迟(似乎他在写第 x+1 行后保存了第 x 行),但这已经给了我实时馈送图。非常感谢,Akhil!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 2014-09-30
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多