写入后的file.tell()在追加模式下不正确?

问题描述 投票:0回答:1

方法

tell()
返回的值低于预期。它并不指向最后写入的字节的位置。

考虑这个例子:

# appender.py
import sys

file = open(sys.argv[1], 'a+b')
file.seek(0)
file.write(b'56789')
print('offset: ', file.tell())
$ printf "01234" > myfile
$ python appender.py myfile
offset:  5

该值应该是 10 而不是 5。

这与 C 中的等价:

/* appender.c */
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char **argv){
  if (argc!=2){
    puts("usage ./test file");
    return 1;
  }
  int fd = open(argv[1], O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR);
  lseek(fd, 0, SEEK_SET);
  write(fd, "01234", 5);
  printf("offset: %ld\n", lseek(fd, 0, SEEK_CUR));
  return 0;
}

返回期望值:

$ printf "01234" > myfile
$ ./appender
offset: 10
python file io posix seek
1个回答
0
投票

根据我的实验,无论文件的查找位置如何,

file.write()
都会附加在文件末尾。

如果我像这样扩展你的例子:

# appender.py
import sys

file = open(sys.argv[1], 'a+b')
file.seek(0)
file.write(b'56789')
file.seek(0)
file.write(b'98765')
print('offset: ', file.tell())

并运行测试:

$ printf "01234" > myfile
$ python appender.py myfile
offset:  5
$ cat myfile
012345678998765

请注意,对

file.seek(0)
的两次调用实际上都被忽略了。

查看打开手册,它提到了关于模式

和 'a' 用于追加(在某些 Unix 系统上,意味着所有写入都追加到文件末尾,无论当前的查找位置如何)

这似乎不仅适用于 Unix 系统,还适用于其他一些系统。我在 Windows 上的 cmd 和 Git Bash 中对此进行了测试。

© www.soinside.com 2019 - 2024. All rights reserved.