Oliver Oliver - 19 days ago 5
Python Question

open file for random write without truncating?

In python, there are a few flags you can supply when opening a file for operation. I am a bit baffled at finding a combination that allow me to do random write without truncating. The behavior I am looking for is equivalent to C: create it if it doesn't exist, otherwise, open for write (not truncating)

open(filename, O_WRONLY|O_CREAT)


Python's document is confusing (to me):
"w"
will truncate the file first,
"+"
is supposed to mean updating, but
"w+"
will truncate it anyway. Is there anyway to achieve this without resorting to the low-level
os.open()
interface?

Note: the
"a"
or
"a+"
doesn't work either (please correct if I am doing something wrong here)

cat test.txt
eee

with open("test.txt", "a+") as f:
f.seek(0)
f.write("a")
cat test.txt
eeea


Is that so the append mode insist on writing to the end?

Answer

You should open in rb+ mode.

with open("file", "rb+") as file:
    file.write(b"...")

On Python 2 you could use r+ instead for text mode, but you shouldn't since it can change the length of the text you write.

Comments