Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python open() flags for open or create

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.

like image 702
ArekBulski Avatar asked Jul 22 '16 16:07

ArekBulski


1 Answers

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
like image 170
user541686 Avatar answered Oct 23 '22 14:10

user541686