从无限 While 循环保存到文本文件

编程入门 行业动态 更新时间:2024-10-17 17:22:41
本文介绍了从无限 While 循环保存到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-26 03:42:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1128657.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!