Skip to content

Instantly share code, notes, and snippets.

@colematt
Last active September 10, 2020 15:55
Show Gist options
  • Save colematt/76222c8df201ca83e8705f02cb2874f1 to your computer and use it in GitHub Desktop.
Save colematt/76222c8df201ca83e8705f02cb2874f1 to your computer and use it in GitHub Desktop.
[Using Context Managers for File I/O] #python #python3
Line 1
Line 2
Line 3
import sys
class myFileReader(object):
def __init__(self, filename):
print("in __init__", file=sys.stderr)
self.f = open(filename)
def __enter__(self):
print("in __enter__", file=sys.stderr)
return self
def readlines(self):
for line in self.f.readlines():
yield line
def __exit__(self,exc_type, exc_value, traceback):
print("in __exit__", file=sys.stderr)
if __name__ == "__main__":
# Demonstration of Context Managers for file reading
#See: https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers
#See: https://www.python.org/dev/peps/pep-0343/
with myFileReader("input.txt") as mfr:
for line in mfr.readlines():
print("readline:", line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment