I have tried my hand at writing a Python context manager that safely opens a file for reading and gracefully deals with a FileNotFound error. Here's my code:
filename = 'my_file.txt'
class SafeRead:
def __init__(self,fname):
self.filename = fname
def __enter__(self):
try:
self.file_handle = open(self.filename,'r')
except Exception as e:
self.file_handle = None
print(e)
return self.file_handle
def __exit__(self,e_type,e_val,e_trace):
if self.file_handle:
self.file_handle.close()
with SafeRead(filename) as f:
if f: data = f.read()
Is it possible to write a context manager that suppresses the execution of the inner block obviating the need for the additional check on the file handle?