open() in Python does not create a file if it doesn't exist
Solution 1:
You should use open
with the w+
mode:
file = open('myfile.dat', 'w+')
Solution 2:
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.