Last active
August 29, 2015 14:21
-
-
Save Yagisanatode/84d96157e22d129cfcfc to your computer and use it in GitHub Desktop.
Python 3 - Opening files Using the "with" Statement
This file contains hidden or 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
"Because I'm BATMAN!" |
This file contains hidden or 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
#! 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