FileObject 读取工作方式与写入类似
让我们看一段简单的代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在写入“Y”之后放置
,则后续的 read(1) 将读取正确的值(在本例中为“A”)。
所以我的猜测是,在 Windows 上 read() 不会强制刷新缓冲区,而在 *nix 上却会强制刷新。
If you put
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.