FileObject 读取工作方式与写入类似

发布于 2024-12-20 13:26:38 字数 410 浏览 3 评论 0原文

让我们看一段简单的代码:

import os

f = open('test.bin', 'wb')
f.write('X')
f.close()
# test.bin - X

f = open('test.bin', 'r+b')

f.seek(0, os.SEEK_END)
f.write('AB')
# test.bin - XAB

f.seek(0, os.SEEK_SET)
f.write('Y')
# test.bin - YAB

print f.read(1)
# test.bin - YBB and prints B 0_o whhyyy?

f.close()

为什么在这种情况下 read 方法像 write 一样工作?
我使用Python 2.5和2.7 for windows从官方网站下载。

Let's see simple piece of code:

import os

f = open('test.bin', 'wb')
f.write('X')
f.close()
# test.bin - X

f = open('test.bin', 'r+b')

f.seek(0, os.SEEK_END)
f.write('AB')
# test.bin - XAB

f.seek(0, os.SEEK_SET)
f.write('Y')
# test.bin - YAB

print f.read(1)
# test.bin - YBB and prints B 0_o whhyyy?

f.close()

Why in that case read method works like write??
I use Python 2.5 and 2.7 for windows download from official site.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

秋风の叶未落 2024-12-27 13:26:38

如果您在写入“Y”之后放置

f.flush()

,则后续的 read(1) 将读取正确的值(在本例中为“A”)。

所以我的猜测是,在 Windows 上 read() 不会强制刷新缓冲区,而在 *nix 上却会强制刷新。

If you put

f.flush()

after you write 'Y' subsequent read(1) reads the correct value (in this case 'A').

So my guess is that on windows read() doesn't force buffers flush while on *nix it does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文