python with open

来源:互联网 发布:淘宝的雷蛇能买吗 编辑:程序博客网 时间:2024/06/10 19:31


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.

shareimprove this answer
 
 
I am using it on GAE, so the question is if it will cost me extra resources since I am not closing the file "correctly" – 1qazxsw2 Nov 4 '11 at 15:41
 
@1qazxsw2 If you use the with statement the file resource will be closed properly for you. – David AlberNov 4 '11 at 15:46
 
@1qazxsw2, the with statement makes sure the file is closed "correctly", it's even better than an explicit close. And it should be available in GAE's Python 2.5. See effbot.org/zone/python-with-statement.htm – Mark Ransom Nov 4 '11 at 15:48
7 
Re first sentence: Python will close it eventually. But that doesn't mean you should forget about closing. Even with refcounting, the file may stay open far longer than you think and want (e.g. if it happens to be referred to by cycles). This goes thrice in Python implementations that have a decent GC, where you have no guarantee that anything is GC'd at any particular time. Even the CPython documentation says you shouldn't rely on GC for cleanup like this. The latter part of the answer should be bold. – delnan Nov 4 '11 at 15:51 
3 
If you really need a one-liner, it is possible to put the output = f.read() part on the same line after the :. – Karl Knechtel Nov 4 '11 at 16:03
up vote10down vote

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.


0 0
原创粉丝点击