简体   繁体   中英

Bug in Python's 'a+' file open mode?

I'm currently making a filesystem using python-fuse and was looking up where file pointers start for each of the different modes ('r', 'r+', etc.) and found on multiple sites that the file pointer starts at zero unless it is opened in 'a' or 'a+' when it starts at the end of the file.

I tested this in Python to make sure (opening a text file in each of the modes and calling tell() immediately) but found that when it was opened in 'a+' the file pointer was at zero not the end of the file.

Is this a bug in python, or are the websites wrong?

For reference:

No, it's not a bug.

What happens when you call tell() after writing some data?

Does it write at position 0, or at the end of file as you would expect? I would almost bet my life that it is the latter.

>>> 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

So, it does seek to the end of the file before it writes data.

This is how it should be. From the fopen() man page:

  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. 

Phew, lucky I was right.

I don't think it's a bug (although I don't exactly understand what this is about). The docs say:

...'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position)

This is indeed what happens:

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!'

I'm on Ubuntu and tell() also returns 0 in a+ mode.

The mode passed to open() is just passed to the C fopen() function. a+ is supposed to set the position of the stream to 0, since the file is opened for both reading and appending. On most unix systems (and possibly elsewhere), all writes will be done at the end of the file regardless of where in the file you've seek() ed to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM