gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:47:06 25 4
gpt4 key购买 nike

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

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从官方网站下载。

最佳答案

如果你放

f.flush()

写入“Y”后,后续的 read(1) 会读取正确的值(在本例中为“A”)。

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

关于python - FileObject 读取工作方式与写入类似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8474394/

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