In the python built-in open function, what is the exact difference between the modes w
, a
, w+
, a+
, and r+
?
In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "updating" specifically, but does not define what these terms mean.
I noticed that every now and then I need to Google fopen all over again, just to build a mental image of what the primary differences between the modes are. So, I thought a diagram will be faster to read next time. Maybe someone else will find that helpful too.
Same info, just in table form
where meanings are: (just to avoid any misinterpretation)
write - writing to file is allowed
create - file is created if it does not exist yet
trunctate - during opening of the file it is made empty (all content of the file is erased)
position at start - after file is opened, initial position is set to the start of the file
Note:
a
anda+
always append to the end of file - ignores anyseek
movements.BTW. interesting behavior at least on my win7 / python2.7, for new file opened in
a+
mode:write('aa'); seek(0, 0); read(1); write('b')
- secondwrite
is ignoredwrite('aa'); seek(0, 0); read(2); write('b')
- secondwrite
raisesIOError
I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would throw an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.
The options are the same as for the fopen function in the C standard library:
w
truncates the file, overwriting whatever was already therea
appends to the file, adding onto whatever was already therew+
opens for reading and writing, truncating the file but also allowing you to read back what's been written to the filea+
opens for appending and reading, allowing you both to append to the file and also read its contentsThe opening modes are exactly the same as those for the C standard library function
fopen()
.The BSD
fopen
manpage defines them as follows:I think this is important to consider for cross-platform execution, i.e. as a CYA. :)
This is directly quoted from Python Software Foundation 2.7.x.