Created
December 19, 2021 18:01
-
-
Save jalcoding8/cbb4f36bd8134887fda90471274c0bfd to your computer and use it in GitHub Desktop.
Building a python class context manager that will write and read file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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