Oliver Oliver - 1 year ago 81
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):
will truncate the file first,
is supposed to mean updating, but
will truncate it anyway. Is there anyway to achieve this without resorting to the low-level

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

cat test.txt

with open("test.txt", "a+") as f:
cat test.txt

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

Answer Source

You should open in rb+ mode.

with open("file", "rb+") as file:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download