Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read the whole file at once

Tags:

python

file

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?
like image 872
georg Avatar asked Dec 17 '22 08:12

georg


1 Answers

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!

like image 80
Nate Avatar answered Dec 28 '22 23:12

Nate