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.