What is the mode for open(..., mode) in Python 3 that opens a file that
I tested r+b
but that fails on missing file, w+b
truncates it, and a+b
seem to turn all writes into appends, while I need to overwrite some data.
open()
!!Python's open()
is like the fopen()
API in C, and neither has this ability.
Note that the try
/except
approach you posted has a race condition:
The file can be created in between the two calls, and suddenly you'll truncate it with the second call.
os.open()
and os.fdopen()
:fd = os.open(path, os.O_CREAT | os.O_RDWR | os.O_BINARY)
if fd != -1:
f = os.fdopen(fd, 'r+b') # Now use 'f' normally; it'll close `fd` itself
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With