linux – open() in Python does not create a file if it doesnt exist

linux – open() in Python does not create a file if it doesnt 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 blocks end, even if an exception is raised on the way. Its 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 files 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.

linux – open() in Python does not create a file if it doesnt exist

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)

Leave a Reply

Your email address will not be published. Required fields are marked *