问题描述
限时送ChatGPT账号..我目前正在将无限 while 循环中的数据写入树莓派上的 SD 卡.
I am currently writing data from an infinite while loop to an SD Card on a raspberry pi.
file = open("file.txt", "w")
while True:
file.write( DATA )
如果程序不是通过命令或键盘中断关闭,有时 file.txt 似乎并不总是保存.是否有定期保存并确保数据被保存的方法?我正在考虑使用
It seems that sometimes file.txt doesn't always save if the program isn't closed through either a command or a keyboard interrupt. Is there a periodic way to save and make sure the data is being saved? I was considering using
open("file.txt", "a")
附加到文件并定期关闭 txt 文件并再次打开它.是否有更好的方法在运行无限 while 循环时安全地存储数据?
to append to file and periodically closing the txt file and opening it up again. WOuld there be a better way to safely store data while running through an infinite while loop?
推荐答案
文件的write()
方法不一定将数据写入磁盘.您必须调用 flush()
方法来确保发生这种情况...
A file's write()
method doesn't necessarily write the data to disk. You have to call the flush()
method to ensure this happens...
file = open("file.txt", "w")
while True:
file.write( DATA )
flle.flush()
不要担心对 os.fsync()
的引用 - 操作系统会假装数据已写入磁盘,即使实际上并没有.
Don't worry about the reference to os.fsync()
- the OS will pretend the data has been written to disk even if it actually hasn't.
这篇关于从无限 While 循环保存到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论