HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
existdoesndoesfilenotopenpythoncreate

Problem

What is the best way to open a file as read/write if it exists, or if it does not, then create it and open it as read/write? From what I read, file = open('myfile.dat', 'rw') should do this, right?

It is not working for me (Python 2.6.2) and I'm wondering if it is a version problem, or not supposed to work like that or what.

The enclosing directory was writeable by user and group, not other (I'm on a Linux system... so permissions 775 in other words), and the exact error was:

IOError: no such file or directory.

Solution

You should use open with the w+ mode:

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

Code Snippets

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

Context

Stack Overflow Q#2967194, score: 1140

Revisions (0)

No revisions yet.