python with open

7 篇文章 0 订阅


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.

share improve 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 Alber Nov 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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值