Does the code below provide correct exception handling. My goal is, to not attempt the file.write() unless the file was successfully opened and ensure the file is closed. I am not concerned with the exact errors of why the file did not open or why the file did not write.
Python version 3.6.9. OS Linux.
data = "Some data"
filename = "test.txt"
try:
file = open(filename, 'w+')
except:
print("Error opening file")
else:
try:
file.write(data)
except:
print("Error writing to file")
finally:
file.close()