contextlib里的closing上下文管理

本文介绍了如何使用Python中的with语句来管理文件资源,包括本地文件和网络资源的读取。通过with语句可以自动确保文件在使用完毕后被正确关闭,并提供了使用contextlib.closing来处理不支持with语句的对象的方法。

推荐使用 "with"语句 以管理文件:
with open("hello.txt") as hello_file:
    for line in hello_file:
        print line
对于不支持使用"with"语句的类似文件的对象,使用 contextlib.closing():
import contextlib
with  contextlib.closing(urllib.urlopen("http://www.python.org/"))  as  front_page:
       for line in front_page:
             print line

创建上下文管理器,在执行过程离开with语句体时自动执行object.close()。

with语句返回的值与object相同

from contextlib import closing

with closing(requests.get('http:xxxxxxxxx.com', stream=True)) as r:

        do something 

closing操作一些网络数据比较多。

 


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值