Fix Python – open read and close a file in 1 line of code

Question

Asked By – 1qazxsw2

Now I use:

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

But to make the code look better, I can do:

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

When using the above syntax, how do I close the file to free up system resources?

Now we will see solution for issue: open read and close a file in 1 line of code


Answer

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.

This question is answered By – Tim Pietzcker

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0