0

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()
  • Look at [What is a good way to handle exceptions when trying to read a file in python?](https://stackoverflow.com/questions/5627425/what-is-a-good-way-to-handle-exceptions-when-trying-to-read-a-file-in-python) – Nilesh Bhave Apr 12 '22 at 04:22
  • A context handler (`with open`) would simplify this. You should basically never use a blanket `except`; always spell out which exception(s) exactly you want to handle. – tripleee Apr 12 '22 at 04:50
  • I have updated my question to make the requirements of the code clearer. – user264427 Apr 12 '22 at 04:52
  • @tripleee I removed the code from the comments. Given the requirements of the code can you supply the correct code using with open ? – user264427 Apr 12 '22 at 05:50
  • Where is `opened_w_error` supposed to come from? – tripleee Apr 12 '22 at 05:51

1 Answers1

1

You should basically never use a blanket except; always spell out which exception(s) exactly you want to handle.

Here is a refactoring using a context handler, so you can avoid the explicit finally: close

data = "Some data"
filename = "test.txt"

try:
    with open(filename, 'w+') as file:
        try:
            file.write(data)
        except (IOError, OSError):
            print("Error writing to file")
except (FileNotFoundError, PermissionError, OSError):
    print("Error opening file")

There may be more exceptions you should enumerate; I rattled these off off the top of my head.

tripleee
  • 158,107
  • 27
  • 234
  • 292