Projects/class_user_def_context_mgr.py
2025-09-12 20:37:36 -07:00

22 lines
825 B
Python

class ManagedFile: # A user-defined context manager for text files
def __init__(self, filename):
self.filename = filename
self.file = None
def __enter__(self):
self.file = open(self.filename, 'w')
print('File opened and written')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file:
self.file.close()
print('Exception:', exc_type, exc_value, traceback)
with ManagedFile('managed_file.txt') as file: # Using the user-defined context manager
note = input("Write some text and Press Enter to continue...\n ")
file.write(note)
print("Managed file has been written and closed automatically.")
# The file is automatically closed after the with block, even if an exception occurs.