Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Open() in Python does not create a file if it doesn't exist

What is the most ideal approach to open a file as reading/writing on the off chance that it exists, or on the off chance that it doesn't, make it and open it as reading/writing? From what I read, record = open('myfile.dat', 'rw') ought to do this, correct?

It isn't working for me (Python 2.6.2) and I'm contemplating whether it is a variant issue, or shouldn't work like that for sure.

The main concern is, I simply need an answer to the issue. I'm interested in the other stuff, yet all I need is a pleasant method to do the initial part.
by

2 Answers

ninja01
You should use open with the w+ mode:

file = open('myfile.dat', 'w+')
RoliMishra
Good practice is to use the following:

import os

writepath = 'some/path/to/file.txt'

mode = 'a' if os.path.exists(writepath) else 'w'
with open(writepath, mode) as f:
f.write('Hello, world!\n')

Login / Signup to Answer the Question.