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

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


You should use open with the w+ mode:

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


The advantage of the following approach is that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.

with open("file.dat","a+") as f:    f.write(...)    ...

a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. -Python file modes

seek() method sets the file's current position.

f.seek(pos [, (0|1|2)])pos .. position of the r/w pointer[] .. optionally() .. one of ->  0 .. absolute position  1 .. relative position to current  2 .. relative position from end

Only "rwab+" characters are allowed; there must be exactly one of "rwa" - see Stack Overflow question Python file modes detail.


Good practice is to use the following:

import oswritepath = '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')