简体   繁体   中英

Python exceptions - a function with try…except clause in a loop

I frequently encounter a situation like this:

import os

for i in range(10):
    os.mkdir(i)

However, sometimes a directory already exists, in which case os.mkdir throws an OSError. When this happens, I just want it to skip the rest of the loop and move to the next iteration of i, so I often write something like this:

for i in range(10):
    try:
        os.mkdir(i)
    except OSError:
        continue

However, what I really, really want is a function which encapsulates that behaviour. Something like this:

def custom_mkdir(directory):
    try:
        os.mkdir(directory)
    except OSError:
        continue

So that I can have some code like this:

for i in range(10):
    custom_mkdir(i)

with the intended behaviour that it makes the directory if it doesn't exist but skips to the next interation of the for loop if it does.

However, the continue statement can't be included in a function in that way. So how do I get the intended behaviour without resorting to:

for i in range(10):
    try:
        custom_mkdir(i)
    except OSError:
        continue

which is an even worse situation than the first?

Well, if there's nothing else going on inside the loop you can just do this:

def custom_mkdir(directory):
    try:
        os.mkdir(directory)
    except OSError:
        pass

for i in range(10):
    custom_mkdir(i)

If there's actually more code below custom_mkdir , I think the best you can do is this:

def custom_mkdir(directory):
    try:
        os.mkdir(directory)
        return True
    except OSError:
        return False

for i in range(10):
    if not custom_mkdir(i):
       continue

or

for i in range(10):
    if custom_mkdir(i):
        # The rest of the logic in here

Which are at least a little more concise than the original.

When OSError is caught inside custom_mkdir , what your function really wants to do is just do nothing. So, do nothing:

def custom_mkdir(directory):
    try:
        os.mkdir(directory)
    except OSError:
        pass

Just return a bool:

def custom_mkdir(directory):
    try:
        os.mkdir(directory)            
    except OSError:
        return False
    return True

for i in range(10):
    if not custom_mkdir(directory): continue

code:

def cusyom_mkdir(diectory):
try:
    os.mkdir(directory)
    return True
except OSError:
    return False

status = map(cusyom_mkdir, [i for i in range(10)])

or

def cusyom_mkdir(diectory):
try:
    os.mkdir(directory)
    return True, directory
except OSError:
    return False, directory

status = map(cusyom_mkdir, [i for i in range(10)])

You can see that the directory is successfully created the directory creation fails

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