'python3 file open write exception handling
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()
Solution 1:[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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | tripleee |