zoukankan      html  css  js  c++  java
  • 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()

  • 相关阅读:
    jquery
    模板库
    Luogu P1902 刺杀大使
    8.20模拟赛再次观光记
    Luogu P1122 最大子树和
    Luogu P1470 最长前缀 Longest Prefix
    8.18爆炸记
    Luogu P1388 算式
    Luogu P1103 书本整理
    8.17
  • 原文地址:https://www.cnblogs.com/yuanjia8888/p/10081591.html
Copyright © 2011-2022 走看看