Read the whole file at once

I am trying to write a function that gets the path and returns this file. No error handling required. I 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 is considered more pythonic?
  • in the second function, will the file be automatically closed with "c"?
  • Is there a better way, maybe some kind of built-in function?
+4
source share
2 answers

They are both pretty pythonic. To solve the second issue, in the second function the file will really be closed automatically. This is part of the protocol used with the operator with. Oddly enough, the file is not guaranteed to be closed in your first example (more on why in a second).

, with, - PEP 343:

with EXPR as VAR:
    BLOCK

:

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)

, - , . ; , , !

+9

, , with :

try:
   f = open(filepath)
   <code>
finally:
   f.close()

, , .


( ):

open(filepath).read()

, , , .

+3
source

All Articles