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
withstatement. 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
withstatement, 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!