read the whole file at once

后端 未结 2 505
情深已故
情深已故 2021-01-19 17:36

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(         


        
相关标签:
2条回答
  • 2021-01-19 18:13

    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!

    0 讨论(0)
  • 2021-01-19 18:17

    I will say the second one , and yes the file will be closed, think of the with statement like this:

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

    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):

    open(filepath).read()
    

    The file will be closed when the file object will be garbage collected, but IMHO explicit is better than implicit.

    0 讨论(0)
提交回复
热议问题