It looks like OpenOptions
does not support this scenario and an existing file will either be truncated or overwritten.
You can use many ways to create a file if it does not exist. The most common way is to use the open() function and pass the different modes as per your requirement. Other ways are using the pathlib module or the os module and checking the file's existing condition.
Python Create File if Not Exists Using the open() Function From the file modes explained above, we can pass a+ to add the text to the file or create it first if it does not exist. The w+ mode will truncate the file and then open it in write mode, so if we do not want the file to be truncated, we should use the a+ mode.
a: It indicates append mode. w+: It's used to create the file if it doesn't already exist, and then it's used to open it in write mode. r+: It opens the required file in both modes (read and write). a+: If the file does not exist, first it is created and afterward opened in append mode.
The fopen() function creates the file if it does not exist. Notes: The fopen() function is not supported for files that are opened with the attributes type=record and ab+, rb+, or wb+ Use the w, w+, wb, w+b, and wb+ parameters with care; data in existing files of the same name will be lost.
As of Rust 1.9.0, there is OpenOptions::create_new
which enables you to safely and atomically ensure that you are creating a new file, and that your command will fail otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With