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:
- which one is considered more pythonic?
- in the second function, will the file be closed automatically by the means of "with"?
- is there a better way, maybe some builtin function?
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:Is translated into:
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!
I will say the second one , and yes the file will be closed, think of the
with
statement like this: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):
The file will be closed when the file object will be garbage collected, but IMHO explicit is better than implicit.