Skip to content

Instantly share code, notes, and snippets.

@worldofprasanna
Last active August 15, 2016 20:22
Show Gist options
  • Save worldofprasanna/cff16b3cc4a1da83463c15c7b8e26387 to your computer and use it in GitHub Desktop.
Save worldofprasanna/cff16b3cc4a1da83463c15c7b8e26387 to your computer and use it in GitHub Desktop.
With statements in Python
# Java style of file handling
# Good example of sandwich code
filename='test.txt'
try:
file = open(filename)
print(file.readlines())
except Exception as e:
print(e.args[0])
finally:
file.close()
# Output
# ['This \n', ' is \n', ' temp\n']
#-----------------------------------------------------------------------------
# Using with statement to read text from file
# file closing will be done automatically
with open('/Users/prasanna/test.txt') as file:
print(file.readlines())
# --------------------------------------------------------------------
# Custom implementation of open
class MyOpen:
def __init__(self, filename):
self.filename = filename
# Gaurd methods
# whatever returns here can be used inside the with block (eg: file)
def __enter__(self):
self.file = open(self.filename)
return self.file
# This magic method will be called once the execution is complete
# if it returns true, then exceptions will be swallowed
def __exit__(self, type, value, traceback):
self.file.close()
# MyOpen can be used in same way as open and we know what is under the hood.
with MyOpen('text.txt') as file:
print(file.readlines())
# http://effbot.org/zone/python-with-statement.htm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment