关于在追加模式下打开文件然后尝试寻找文件的开头,我遇到了这种奇怪的行为.
代码应该是不言自明的:在第二次打开时,我希望能够在文件的开头写一个字符串然后让f.tell()返回5(在文件开头写的字节数) ).
问题是,在Python 2.6.6和2.7.6中,最终的断言触发,但令人惊讶的是,它在Python 3.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版本:
#include
int main() {
FILE *f = fopen("tt", "w+b");
fseek(f, 100, 0);
fwrite("x", 1, 1, f);
fclose(f);
f = fopen("tt", "a+b");
fseek(f, 0, 0);
fwrite("y", 1, 1, f);
printf("%ld\n", ftell(f));
fclose(f);
return 0;
}
这打印102,我认为这是规范的(我看过strace -eopen,close,lseek输出,但不是更聪明).
所以我的问题是:我没有什么样的令人尴尬的基本知识?
为什么Python 3的行为有所不同?
顺便说一下,我在Linux上.