You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

追加模式下file.tell()写入后返回值不符合预期的技术问询

Python文件对象的tell()方法返回值不符合预期

当以a+b模式打开文件时,调用tell()返回的偏移量并未指向最后写入字节的位置,结果低于预期值。

Python示例代码

# 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

这里返回的偏移量为5,但预期值应为10(原文件含5字节,写入5字节后总长度为10)。

等效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;
}

C代码运行结果

$ printf "01234" > myfile
$ ./appender myfile
offset: 10

C语言实现返回了符合预期的偏移量10。

内容的提问来源于stack exchange,提问作者Isidro Arias

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:57:11