I'm trying to write a function that gets a path and returns this file's content. No error handling needed. I've came up with the following
def read_all_1(path):
f = open(path)
s = f.read()
f.close()
return s
def read_all_2(path):
with open(path) as f:
return f.read()
My questions:
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 = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if 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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With