with语句

1 try:
2     with open('data.txt') as f #等价于f = open('data.txt','w') 
3         for each_line in f:
4             print(each_line)
5         
6 except OSError as reason: #使用异常处理执行到这一步时边不会再执行后面的语句,因此常常是f.close()不能执行而出问题,上面的with语句可以有效解决该问题
7 print('出错啦'+str(reason))


使用with语句可以处理多个项目用 ‘,’隔开,例如

with A() as a:

  with B() as b:

    suite

可以写成:

with A() as a, B() as b:
  suite

 

posted @ 2017-02-17 08:07  道高一尺  阅读(224)  评论(0编辑  收藏  举报