Home > Mobile >  python3 file open write exception handling
python3 file open write exception handling

Time:04-12

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()

CodePudding user response:

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.

  • Related