Skip to content

Instantly share code, notes, and snippets.

@jalcoding8
Created December 19, 2021 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jalcoding8/cbb4f36bd8134887fda90471274c0bfd to your computer and use it in GitHub Desktop.
Save jalcoding8/cbb4f36bd8134887fda90471274c0bfd to your computer and use it in GitHub Desktop.
Building a python class context manager that will write and read file
class PoemFiles:
def __init__(self, poem_file, mode):
print('Starting up a poem context manager')
self.file = poem_file
self.mode = mode
def __enter__(self):
print('Opening poem file')
self.opened_poem_file = open(self.file, self.mode)
return self.opened_poem_file
def __exit__(self, *exc):
print('Closing poem file')
self.opened_poem_file.close()
with PoemFiles('poem.txt', 'w') as open_poem_file:
open_poem_file.write('Hope is the thing with feathers')
#I added the code below to confirm the 'write' content was confirmed
with PoemFiles('poem.txt', 'r') as open_poem_file_again:
print(open_poem_file_again.read()) #if read() not included, the ouput is the class object
#Output
"""Starting up a poem context manager
Opening poem file
Closing poem file
Starting up a poem context manager
Opening poem file
Hope is the thing with feathers
Closing poem file"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment