Read The Whole File At Once
Solution 1:
They are both quite pythonic. To address your second question, in the second function, the file will indeed be closed automatically. That is part of the protocol used with the with
statement. Ironically, the file is not guaranteed to be closed in your first example (more on why in a second).
Ultimately, I would choose to use the with
statement, and here's why - according to PEP 343:
with EXPR as VAR:
BLOCK
Is translated into:
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = Truetry:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = Falseifnot exit(mgr, *sys.exc_info()):
raise# The exception is swallowed if exit() returns truefinally:
# The normal and non-local-goto cases are handled hereif exc:
exit(mgr, None, None, None)
As you can see, you get a lot of protection in this case - your file is guaranteed to be closed no matter what happens in the intervening code. This also really helps for readability; imagine if you had to put this huge block of code every time you wanted to open a file!
Solution 2:
I will say the second one , and yes the file will be closed, think of the with
statement like this:
try:
f = open(filepath)
<code>
finally:
f.close()
About your third question no there is no other way that don't involve opening the file.
A third way can be (without explicitly closing the file):
open(filepath).read()
The file will be closed when the file object will be garbage collected, but IMHO explicit is better than implicit.
Post a Comment for "Read The Whole File At Once"