【问题标题】:What is the difference between with and if in Python2?Python2中的with和if有什么区别?
【发布时间】:2018-03-26 20:54:20
【问题描述】:

我正在查看使用此代码的 INI 配置文件实现 here:

# Load the configuration file
with open("config.ini") as f:
    sample_config = f.read()
    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.readfp(io.BytesIO(sample_config))

如果找不到配置文件,我想输出一些东西,但the Python documentation 没有说明else 条件,所以我想在这里使用if...else 块:

# Load the configuration file
if f = open("config.ini"):
    sample_config = f.read()
    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.readfp(io.BytesIO(sample_config))
else
    print "Could not open config file"

使用if...else 块代替with 块我会看到什么样的差异?

【问题讨论】:

    标签: python python-2.7 if-statement with-statement


    【解决方案1】:

    嗯,一个区别是if 块不会解析。赋值语句不是 Python 中的表达式。另一个是它不会自行关闭文件 - that’s what the with accomplishes。

    你真正要找的是try,因为当找不到文件时open 会抛出异常:

    try:
        # Load the configuration file
        with open("config.ini") as f:
            config = ConfigParser.RawConfigParser(allow_no_value=True)
            config.readfp(f)
    except FileNotFoundError:
        # handle exception
    

    (如果您使用的是旧版本的 Python,则需要捕获 OSError 和 check its errno。)

    【讨论】:

      【解决方案2】:

      测试一个条件是否为真,然后在满足条件后执行代码块示例:

      a = 1
      if a != 1:
          do something here.
      elif a ==1: # elif takes the place of else, literally means else if a ==/!= some value execute this.
          do something else.
      

      With 语句是一个布尔运算,它可以与文件 I/O 一起使用,或者这是我见过的最多使用的。

      示例可能是:

      with open(somefile):
          do some stuff.
      

      我所看到的 else 子句似乎只适用于条件从未满足时的 try/if 语句的最后,它的用途基本上是,如果 try 语句由于某种原因失败,则就是你现在执行的。

      with open(somefile):
          try:
              do stuff.
      else:
      exit loop/ do something else.
      

      ------------------------------------------ ------------------------------------

      说实话,我喜欢 while 语句的轻松。您可以在 while 循环、for 循环、if 循环(我喜欢嵌套循环)中嵌套更多条件语句,它们大大简化了编写代码的过程。

      这是我不久前写的一段代码sn-p:

      while continue_loop == 'Y': # gives user an option to end the loop or not 
                                  # and gives you more flexibility on how the loop runs.
          ac = 0
          acc = 0
          accu = 0
          accum = 0
          try: # the try block, gets more info from user, and stores it inside variables.
              bday = int(input("Please enter the day you were born! \n->"))
              bmonth = int(input("Please enter the month you were born\n ->"))
              byear = int(input("Please enter the year you were born!\n->"))
              birth = bday + bmonth + byear
              sum1 = str(birth)
              for x in sum1: # iteration over the variable.
                  accum1 += int(x)
                  accum2 = str(accum1)
      

      【讨论】:

        猜你喜欢
        • 2012-05-14
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-12
        • 2016-10-13
        • 2017-09-07
        相关资源
        最近更新 更多