## Example 1: Without 'with' statement
file = open("sample.txt")
print(file.read())
file.close()
# here if any exception is raised before line 4
# the 'file.close()' will not be executed
## Example 2: Closing the file using 'try..finally'
try:
file = open("sample.txt")
print(file.read())
finally:
file.close()
# here even if a exception is raised the file is going be closed
## Example 3: Now doing same as above example using 'with' statement
with open("sample.txt") as f:
print(f.read())
# Notice: No need to call 'close()' method, 'with' has you covered
## Example 4: But if you want to handle exceptions use your own
# 'try..except..finally'
try:
file = open("sample.txt")
print(file.read())
except Exception as e:
print(e)
finally:
file.close()