open read and close a file in 1 line of code

前端 未结 11 1339

Now I use:

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

But t

11条回答
  •  北海茫月
    2020-11-28 05:59

    You don't really have to close it - Python will do it automatically either during garbage collection or at program exit. But as @delnan noted, it's better practice to explicitly close it for various reasons.

    So, what you can do to keep it short, simple and explicit:

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

    Now it's just two lines and pretty readable, I think.

提交回复
热议问题