From what I understand, the statement uses try and then opens the file, processes it and closes it. How efficient is that?
This file contains 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 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!" | |
>>> | |
""" |
To learn more about the with statement:
http://effbot.org/zone/python-with-statement.htm
No comments:
Post a Comment