with 和 if in Python2 有什么区别?

What is the difference between with and if in Python2?

我正在查看使用此代码的 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 块会有什么不同?

嗯,一个区别是 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,则需要捕获 OSErrorcheck its errno。)

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

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.

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

示例可以是:

with open(somefile):
    do some stuff.

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

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

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

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

这是我不久前写的一篇文章的代码片段:

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)