gpt4 book ai didi

Python:file.write() 与 file.flush()

转载 作者:行者123 更新时间:2023-12-01 03:17:33 26 4
gpt4 key购买 nike

file.write() 和 file.flush() 之间到底有什么区别?

来自Python's official documentation ,我明白了:

flush() Force bytes held in the buffer into the raw stream. A BlockingIOError should be raised if the raw stream blocks.

write(b) Write the bytes-like object, b, and return the number of bytes written. When in non-blocking mode, a BlockingIOError is raised if the buffer needs to be written out but the raw stream blocks.

据我的新手了解,它们都将当前保存在内存中的信息传输到磁盘上的文件。但不同之处在于 write() 还返回有关存储了多少信息的信息,而 flash() 立即执行此任务。那是对的吗?在什么情况下应用 write() 优于使用lush(),反之亦然?

最佳答案

[另请参阅 Stephen Rauch 和 Peter Wood 的评论]在一个流的上下文中考虑它,该流连接到另一端从该流读取的内容。

write(b) 将 b 贡献给您端的该流的缓冲区。它实际上可能会或可能不会将所有这些字节放入其中,以便将它们沿着流“发送”到另一端的读取器。

另一方面,flush() 获取流缓冲区中的所有内容,并将其“发送”给读取器。

基本上,您使用 write(b) 将数据加载到流中,然后最后全部使用 flush() 以确保所有内容实际上都已进入底层流并“已发送”,而不是坐等在流的缓冲区中。

因此,例如,如果我使用 PySerial 包将我的计算机连接到另一个设备(它创建一个有效地作为流工作的串行连接),那么为了将一些数据放入该流中,我将使用 write(b) 。然而,为了确保所有数据都已通过串行连接并到达另一个设备,我将调用flush()。这是因为 write(b) 不能保证所有(或事实上的任何)数据实际上会立即发送到其他设备。

关于Python:file.write() 与 file.flush(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42321301/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com