tags:

views:

67

answers:

2

I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this?

I tried 'r+ab' but that doesn't create the files if they are not found.

Thanks

+1  A: 
open("filename", "a+b")

should work. It opens a binary file in append/update mode.

Tim Pietzcker
+3  A: 

The mode is ab+ the r is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) file is based on the C stdio FILE type, here are the relevant lines from the fopen(3) man page:

  • w+ Open for reading and writing. The file is created if it does not exist, otherwise it is truncated. The stream is positioned at the beginning of the file.

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

With the "b" tacked on to make DOS happy. Presumably you want to do something like this:

>>> f = open('junk', 'ab+')
>>> f
<open file 'junk', mode 'ab+' at 0xb77e6288>
>>> f.write('hello\n')
>>> f.seek(0, os.SEEK_SET)
>>> f.readline()
'hello\n'
>>> f.write('there\n')
>>> f.seek(0, os.SEEK_SET)
>>> f.readline()
'hello\n'
>>> f.readline()
'there\n'
msw
Works. Also thanks for pointing out os.SEEK_SET in your example. I think I tried opening the file with a+ before but couldn't read anything out of it. Didn't cross my mind the stream was placed at the end of the file...
MihaiD
Keep in mind that you *must* *always* seek between a read and a write, or a write and a read. Forgetting to do so will usually work on most systems, but not (for example) on Windows.
Thomas Wouters