8

What is the mode for open(..., mode) in Python 3 that opens a file that

  • create if does not exist
  • do NOT truncate
  • binary mode

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.

ArekBulski
  • 4,520
  • 4
  • 39
  • 61
  • 1
    Your answer introduces a race condition. See the other answer for an explanation. You should consider editing or changing the accepted answer – finefoot Jul 05 '21 at 23:30

2 Answers2

8

This is a massive deficiency in C & Python. There's no way to do this via 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.

However: you can achieve what you want using 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
Community
  • 1
  • 1
user541686
  • 205,094
  • 128
  • 528
  • 886
1

A workaround is to catch the exception and open with another mode. I would still accept a better solution.

try:
    self.file = open(filename, "r+b")
except FileNotFoundError:
    self.file = open(filename, "w+b")
ArekBulski
  • 4,520
  • 4
  • 39
  • 61