open read and close a file in 1 line of code

前端 未结 11 1335

Now I use:

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

But t

11条回答
  •  失恋的感觉
    2020-11-28 05:44

    Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:

    1. In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.

    2. In Python 3.2 or above, this will throw a ResourceWarning, if enabled.

    Better to invest one additional line:

    with open('pagehead.section.htm','r') as f:
        output = f.read()
    

    This will ensure that the file is correctly closed under all circumstances.

提交回复
热议问题