tags:

views:

253

answers:

5

I am using Python.

What is the best way to open a file in rw if it exists, or if it does not, then create it and open it in rw? From what i read, file = open('myfile.dat', 'rw') should do this, no? it is not working for me (python 2.6.2) and im wondering if it is a version problem, or not supposed to work like that or what.

The bottom line is, i just need a solution for the problem. I am curious about the other stuff, but all i need is a nice way to do the opening part.

UPDATE: the enclosing dir was writable by user and group, not other (im on a linux system... so permissions 775 in other words), and the exact error was IOError: no such file or directory.

+1  A: 

open('myfile.dat', 'a') works for me, just fine.

in py3k your code raises ValueError:

>>> open('myfile.dat', 'rw')
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    open('myfile.dat', 'rw')
ValueError: must have exactly one of read/write/append mode

in python-2.6 it raises IOError.

SilentGhost
+2  A: 

Change "rw" to "w+"

Or use 'a+' for appending (not erasing existing content)

baloo
+1  A: 

You should use file = open('myfile.dat', 'w+')

muksie
`w` truncates existing file. docs: *Modes `'r+'`, `'w+'` and `'a+'` open the file for updating (note that `'w+'` truncates the file).*
SilentGhost
this did the trick. thank you. i feel like an idiot now for not reading the spec. i dont think 'rw' is even acceptable there. i must have been thinking of something else.
Toddeman
A: 
>>> import os
>>> if os.path.exists("myfile.dat"):
...     f = file("myfile.dat", "r+")
... else:
...     f = file("myfile.dat", "w")

r+ means read/write

Khorkrak
A: 

What do you want to do with file? only writing to it or both read and write?

'w', 'a' will allow write, and will create the file if it doesn't exist.

If you need to read from a file, the file has to be exist before open it. You can test its existence before open it or use a try/catch.

Testing for existence before opening might introduce a race condition. Probably not a big deal in this case, but something to keep in mind.
Daniel Hepper