Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的Bug';s';a和x2B';文件打开模式?_Python_File_File Io_Python 2.7_Mode - Fatal编程技术网

Python中的Bug';s';a和x2B';文件打开模式?

Python中的Bug';s';a和x2B';文件打开模式?,python,file,file-io,python-2.7,mode,Python,File,File Io,Python 2.7,Mode,我目前正在使用python fuse制作一个文件系统,并且正在查找每个不同模式(“r”、“r+”等)的文件指针的起始位置,并在多个站点上发现文件指针的起始位置为零,除非在文件末尾以“a”或“a+”打开 我在Python中对此进行了测试以确保(在每种模式下打开一个文本文件并立即调用tell()),但发现在“a+”中打开时,文件指针位于零,而不是文件的末尾 这是python中的错误,还是网站错了 供参考: (搜索“文件指针”) 我正在Ubuntu上使用Python 2.7.3 我不认为这是一个bu

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

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

这是python中的错误,还是网站错了

供参考:

  • (搜索“文件指针”)
  • 我正在Ubuntu上使用Python 2.7.3
    • 我不认为这是一个bug(尽管我不太明白这是怎么回事)。文件说:

      …用于追加的“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

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

      不,这不是错误

      写入一些数据后调用
      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()
      手册页:


      呸,幸运的是我是对的。

      唯一有意义的方法是你打开的文件是一个全新的文件。我可以确认我在Ubuntu上的CPython2.6中看到了这种行为。PyPy似乎可以根据需要打开到文件末尾。Centos 6上的Python 2.6.6也可以根据需要执行。感谢您的清理。我知道它只会将数据写到末尾,但找不到指定起始位置的任何地方。再次感谢你的帮助。
         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.