问题
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.
回答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")
回答2:
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
来源:https://stackoverflow.com/questions/38530910/python-open-flags-for-open-or-create