Saturday, 23 May 2015

Python 3 - Opening files Using the "with" Statement

I just learnt how to save a few lines when opening files in Python 3 using the with statement.

From what I understand, the statement uses try and then opens the file, processes it and closes it. How efficient is that?

"Because I'm BATMAN!"
view raw example.txt hosted with ❤ by GitHub
#! 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!"
>>>
"""
view raw WithOpen.py hosted with ❤ by GitHub


To learn more about the with statement:
http://effbot.org/zone/python-with-statement.htm

No comments:

Post a Comment