如何打开文件进行读写,如果不存在则创建它,如果存在则不截断它?

How to open a file for reading and writing, create it if doesn't exist yet, and if it does, then without truncating it?

所以似乎不可能一次调用 Python 内置函数 open 就可以做到这一点?我将需要使用多个调用并确保不会在两者之间引入竞争条件?

有一点low-level帮手:

import os

def open_create(name, flags):
    return os.open(name, flags | os.O_CREAT)

with open("./testfile", 'r+', opener=open_create) as f:
    ... read/write ...