open read and close a file in 1 line of code

前端 未结 11 1375

Now I use:

pageHeadSectionFile = open(\'pagehead.section.htm\',\'r\')
output = pageHeadSectionFile.read()
pageHeadSectionFile.close()

But t

11条回答
  •  星月不相逢
    2020-11-28 05:52

    I think the most natural way for achieving this is to define a function.

    def read(filename):
        f = open(filename, 'r')
        output = f.read()
        f.close()
        return output
    

    Then you can do the following:

    output = read('pagehead.section.htm')
    

提交回复
热议问题