简体   繁体   中英

What is the difference between with and if in Python2?

I was looking at an INI configuration file implementation here that used this code:

# 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))

I want to output something if the configuration file can not be found, but the Python documentation doesn't say anything about an else condition, so I was thinking of using an if...else block here instead:

# 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"

What kind of differences would I see with an if...else block in place of a with block?

Well, one difference is that the if block would not parse. Assignment statements aren't expressions in Python. Another is that it wouldn't close the file by itself – that's what the with accomplishes .

What you're really looking for is try , since open throws an exception when a file can't be found:

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

(If you're using an older version of Python, you'll need to catch OSError and check its errno instead.)

One tests a condition to see if it is true, then executes the code block after the condition is met example:

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 statement is a boolean operation, it can be used with file I/O, or that's the most that I have seen it used with.

example could be:

with open(somefile):
    do some stuff.

the else clause from what i have seen only seems to work with try/the very end of if statements when the condition has never been met, and its use is basically, if the try statement fails for some reason or another, this is what you now execute.

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

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

Truth be told, I enjoy the ease of while statements. You can nest more conditional statements inside the while loop, for loops, if loops(I have come to LOVE nested loops) they ease the process of writing code so much.

Here is a code snippet from a piece that I wrote not too long ago:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM