Skip to content

Instantly share code, notes, and snippets.

@Yagisanatode
Last active August 29, 2015 14:21
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 Yagisanatode/84d96157e22d129cfcfc to your computer and use it in GitHub Desktop.
Save Yagisanatode/84d96157e22d129cfcfc to your computer and use it in GitHub Desktop.
Python 3 - Opening files Using the "with" Statement
"Because I'm BATMAN!"
#! Python 3.4
### using the "with" statment to open a file###
"""Two ways to open a file"""
""" The old way """
file = open('example.txt', 'r')
read_file = file.read()
print (read_file)
file.close()
""" Or more properly, I guess. """
try:
file = open('example.txt', 'r')
read_file = file.read()
print (read_file)
finally:
file.close()
""" Using the 'with'statement:
This opens the file, processes it and closes it"""
with open('example.txt', 'r') as file:
read_file = file.read()
print (read_file)
"""
RESULT:
>>>
"Because I'm Batman!"
"Because I'm Batman!"
"Because I'm Batman!"
>>>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment