我遇到过这种奇怪的行为,即在append模式下打开一个文件,然后试图寻找文件的开头。在
代码应该是不言自明的:在第二次打开时,我希望能够在文件的开头写入一个字符串,然后让f.tell()返回5(在文件开头写入的字节数)。在
问题是,在Python2.6.6和2.7.6中,final assert会触发,但令人惊讶的是,它在Python3.3.2中工作。在# Create new file, write after the 100th byte.
f = open("test", "w+b")
f.seek(100, 0)
f.write(b"end")
assert f.tell() == 100 + len("end")
f.close()
# Open file for writing without overwriting, attempt to write at start of file
# of the file, but doesn't.
f = open("test", "a+b")
f.seek(0, 0)
f.write(b"start")
assert f.tell() == len("start")
f.close()
所以我做了一个C程序来做同样的事情。实际上,它的行为类似于Python 2.x版本:
^{pr2}$
这将打印102,我认为这是规范的(我也看过strace -eopen,close,lseek输出,但没有一个更聪明)。在
所以我的问题是:我没有什么令人尴尬的基础知识?在
为什么Python3会有不同的行为呢?在
顺便说一下,我用的是Linux。在