简体   繁体   English

如何使循环写入文件python

[英]how to make a loop that writes to a file python

I'm trying to save the currency rates I get from the yahoo finance API to a .txt file as a while loop while the other thread is reading it and writing a graph with it. 我试图将从yahoo财务API获得的货币汇率保存为while循环的.txt文件,而另一个线程正在读取它并使用它编写图形。 For some reason it won't write to the file so the entire program won't work 由于某种原因,它不会写入文件,因此整个程序将无法工作

def thread(spot=1):
    while spot >60:
        savedFile.write(str(currencies.get_rate()) + ',' + str(spot) + '\n')
        spot += 1
        time.sleep(1)

While the data is in the buffer, you can't read it into the other thread. 当数据在缓冲区中时,您无法将其读入另一个线程。 You should flush the file. 您应该flush文件。 The tells the OS to push the buffer to disk. 告诉操作系统将缓冲区推送到磁盘。

def thread(spot=1):
    while spot >60:
        savedFile.write(str(currencies.get_rate()) + ',' + str(spot) + '\n')
        savedFile.flush()
        spot += 1
        time.sleep(1)

Try giving stricter limitations to the loop. 尝试对循环设置更严格的限制。 If you want it to write until it drops below 60 then give a maximum number to write to the file. 如果您希望它写入直到跌落到60以下,则给出一个最大数目以写入文件。 One way to do it would be with an if statement and use the same counter. 一种方法是使用if语句并使用相同的计数器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM