python - Python 的 'a+' 文件打开模式中的错误?

标签 python file file-io python-2.7 mode

我目前正在使用 python-fuse 制作一个文件系统,并正在查找每种不同模式(“r”、“r+”等)的文件指针的起始位置,并在多个站点上找到文件指针的起始位置在零,除非它在文件末尾开始时以 'a' 或 'a+' 打开。

我在 Python 中对此进行了测试以确保(在每种模式下打开一个文本文件并立即调用 tell())但是发现当它在 'a+' 中打开时文件指针为零而不是结尾文件。

这是 python 中的错误,还是网站有误?

供引用:

最佳答案

不,这不是错误。

当您调用 tell() after 写入一些数据时会发生什么?

它是在位置 0 处写入,还是像您预期的那样在文件末尾写入?我几乎敢打赌是后者。

>>> f = open('test', 'a+')
>>> f.tell()
0
>>> f.write('this is a test\n')
>>> f.tell()
15
>>> f.close()
>>> f = open('test', 'a+')
>>> f.tell()
0
>>> f.write('this is a test\n')
>>> f.tell()
30

因此,它确实会在写入数据之前寻找到文件末尾。

这是应该的。来自 fopen() 手册页:

   a+     Open for reading and appending (writing at end  of  file).   The
          file is created if it does not exist.  The initial file position
          for reading is at the beginning  of  the  file,  but  output  is
          always appended to the end of the file.

呸,幸运的是我是对的。

关于python - Python 的 'a+' 文件打开模式中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11016825/

相关文章:

java - 运行时优化

计算文件中数组的长度

c# - 在ASP.NET中,如何让浏览器将字符串内容下载到文件中? (C#)

java - 将二进制文件读入字符串

c# - 输入不是有效的 Base64 字符串,因为它包含非 base 64 字符

python - Python3 中的 numpy 点和 matmul 函数有什么区别?

python - 将 os.system 的输出分配给一个变量并阻止它显示在屏幕上

python - 根据另一列中的 2 行计算列行

python - pandas:将函数应用于数据框列中的每个唯一元素并合并回输出

file - 如何使用Erlang文件:read_file_info permissions/mode info?