open read and close a file in 1 line of code

前端 未结 11 1374

Now I use:

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

But t

11条回答
  •  半阙折子戏
    2020-11-28 06:08

    What you can do is to use the with statement, and write the two steps on one line:

    >>> with open('pagehead.section.htm', 'r') as fin: output = fin.read();
    >>> print(output)
    some content
    

    The with statement will take care to call __exit__ function of the given object even if something bad happened in your code; it's close to the try... finally syntax. For object returned by open, __exit__ corresponds to file closure.

    This statement has been introduced with Python 2.6.

提交回复
热议问题