Python open() flags for open or create

大兔子大兔子 提交于 2020-06-27 15:00:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!