python with open as_优雅地使用Python的with as语句

Python从2.5版本开始支持with as语句,我们也称之为上下文管理器(context manager)。

来看一段docstring:

"""

Python’s with statement was first introduced five years ago,

in Python 2.5. It’s handy when you have two related operations which you’d like to execute as a pair,

with a block of code in between. The classic example is opening a file, manipulating the file, then closing it:

with open('output.txt', 'w') as f:

f.write('Hi there!')

The above with statement will automatically close the file after the nested block of code.

(Continue reading to see exactly how the close occurs.)

The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits.

If an exception occurs before the end of the block,

it will close the file before the exception is caught by an outer exception handler.

If the nested block were to contain a return statement, or a continue or break statement,

the with statement would automatically close the file in those cases, too.

"""

解释的蛮清楚的。

使用with as语句打开一个文件进行操作,无论发生什么情况,这个文件都会保证执行close动作(with as代码块发生异常,return,continue,break)。

江湖上说,使用with as语句写出来的Python代码,很优雅!

使用with as的原理是:

with 语句包裹起来的代码块,在执行语句体之前会调用上下文管理器的 __enter__() 方法,执行完语句体之后会执行 __exit__() 方法。

上下文管理器(Context Manager):支持上下文管理协议的对象,这种对象实现了__enter__() 和 __exit__() 方法。上下文管理器定义执行 with 语句时要建立的运行时上下文,负责执行 with 语句块上下文中的进入与退出操作。通常使用 with 语句调用上下文管理器。

file对象就是一个context manager!

但是,使用with as还是有可能抛出异常,打开文件操作正确的写法是:

try:

with open( "a.txt" ) as f :

do something

except xxxError:

do something about exception

还有以一种情况,文件打开之后要执行的操作不能放在一个连续的代码快中,这时,就只能直接使用open打开,记得自己在逻辑的最后close。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值