【问题标题】:Bug in Python's 'a+' file open mode?Python 的“a+”文件打开模式中的错误?
【发布时间】:2012-06-16 12:36:55
【问题描述】:

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

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

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

供参考:

【问题讨论】:

  • 唯一有意义的方法是您打开的文件是一个全新的文件。否则肯定有bug。
  • 我可以确认我在 Ubuntu 上的 CPython 2.6 中看到了这种行为。 PyPy 似乎可以根据需要打开到文件末尾。
  • Centos 6 上的 Python 2.6.6 也可以正常运行。

标签: python file file-io python-2.7 mode


【解决方案1】:

不,这不是错误。

在写入一些数据之后调用tell()会发生什么?

它是写在位置 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.

呸,幸好我是对的。

【讨论】:

  • 感谢您解决这个问题。我知道它只会将数据写入末尾,但找不到指定起始位置的任何地方。再次感谢您的帮助。
【解决方案2】:

我不认为这是一个错误(尽管我并不完全理解这是什么意思)。文档说:

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

确实是这样的:

In [3]: hello = open('/tmp/hello', 'w')

In [4]: hello.write('Hello ')

In [5]: hello.close()

In [6]: world = open('/tmp/hello', 'a+')

In [7]: world.write('world!')

In [8]: world.close()

In [9]: open('/tmp/hello').read()
Out[9]: 'Hello world!'

我在 Ubuntu 上,tell() 也在 a+ 模式下返回 0

【讨论】:

    【解决方案3】:

    传递给open() 的模式只是传递给C 的fopen() 函数。 a+ 应该将流的位置设置为 0,因为文件是为读取和追加而打开的。在大多数 unix 系统(可能还有其他地方)上,所有写入都将在文件末尾完成,无论您 seek()ed 到文件的哪个位置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-22
      • 2013-01-16
      • 2013-08-19
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多