With语句是什么

https://www.cnblogs.com/DswCnblog/p/6126588.html     #大神写的

有一些事情,需要预先设置, 事后做清理工作,对于这种场景。python 有了with as 方法。例如打开文件

  1、

  file = open("/tmp/foo.txt")  #打开

  data = file.read()   #读

  file.close()  #关闭

  这样会有两个问题, 1、忘记关闭,读取的时候发生异常

 

  2、file = open("/tmp/foo.txt")

     try:

      data = file.read()

    finally:

      file.close()

  3、with可以很好的处理上下文产生的异常、可以完美的解决两个问题、1、读取的时候产生的异常、2关闭问题

  with open("/tmp/foo.txt") as file:

    data = file.read()

猜你喜欢

转载自www.cnblogs.com/yuanjia8888/p/10081591.html
今日推荐