关于 write() 和 truncate() 的 Python 问题 [英] Python question about write() and truncate()

查看:26
本文介绍了关于 write() 和 truncate() 的 Python 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Mac 上的终端中,我正在学习如何打开、关闭、读取、删除文件.

I am in Terminal on mac and I am learning how to open, close, read, delete files.

当我设置

f = open("sample.txt", 'w')

然后点击f.truncate()删除内容.

但是,当我执行 f.write() 时,它不会在文本文件中更新.它仅在我执行 f.truncate() 后更新.

However, when I do f.write() it does not update in the text file. It only updates after I do f.truncate().

我想知道为什么会发生这种情况(我认为 f.truncate() 应该删除文本!)?为什么当我输入 f.write() 时文本编辑器没有自动更新?

I was wondering why this happens (I thought f.truncate() was supposed to delete the text!)? Why doesn't the text editor update automatically when I type in f.write() ?

推荐答案

f.write() 写入 Python 进程自己的缓冲区(类似于 C fwrite()> 功能).但是,在您调用 f.flush()f.close() 或缓冲区填满之前,数据实际上不会刷新到操作系统缓冲区中.完成此操作后,所有其他应用程序都可以看到这些数据.

f.write() writes into the Python process's own buffer (similarly to the C fwrite() functions). However, the data is not actually flushed into the OS buffers until you call f.flush() or f.close(), or when the buffer fills up. Once you do that, the data becomes visible to all other applications.

请注意,操作系统执行另一层缓冲/缓存 -- 所有正在运行的应用程序共享.当文件被刷新时,它被写入这些缓冲区,但直到一段时间过去或当你调用 fsync() 时才会写入磁盘.如果您的操作系统崩溃或计算机断电,此类未保存的更改将会丢失.

Note that the OS does another layer of buffering/caching -- that is shared by all running applications. When the file is flushed, it's written to these buffers, but is not yet written to the disk until some time has passed, or when you call fsync(). If your OS crashes or computer loses power, such unsaved changes will be lost.

这篇关于关于 write() 和 truncate() 的 Python 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆