read the whole file at once

后端 未结 2 508
情深已故
情深已故 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: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)
       
    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.

提交回复
热议问题