I want to read data from a file without truncating it. I know I can use 'r' for reading.
But I also want to create the file if a FileNotFoundError is raised.
But using 'w', 'w+', 'a+' to create a file works, it also truncates any existing data in the file in later runs.
Basically looking for a replacement for:
try:
with open('filename', 'r') as file:
#if no error is raised, file already exits and
#can be read from: do stuff on file.
except FileNotFoundError:
with open('filename', 'x') as file:
pass
#no further actions are required here as the file
#is just being created
Answer at:
open file for random write without truncating?
states that I should open the file in 'rb+' mode, however 'rb+' raises a FileNotFoundError and does not create the file if it doesn't exist.
opening files in binary mode is also not suited for reading text files.