open read and close a file in 1 line of code
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?
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.
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:
In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.
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.
What you can do is to use the with
statement:
>>> with open('pagehead.section.htm', 'r') as fin:
... output = fin.read()
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.
链接地址: http://www.djcxy.com/p/19628.html上一篇: 为每次击中返回周围线路
下一篇: 用1行代码打开读取和关闭文件