A more elegant way to control rewriting with try-except-else in python? or can I do better than C style code?

I have code that creates a folder and puts the output files into it. I want to use the try-except-else block and the rewrite option, which can be set to True or False, so if the folder already exists and the overwrite is set to false, it just prints out that the folder already exists, and in In all other cases, it will be executed without comment.

The only solution I came up with is:

def function( parameters, overwrite = False ):
    try:
        os.makedirs( dir )
    except OSError:
        if overwrite:
            data making code...
        else:
            print dir + ' already exists, skipping...'
    else:
        if overwrite:
            data making code...

, ? , , , ? , C Pythonic.

0
3

( )

import os, errno

def mkdir(path, overwrite=False):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            if not overwrite:
                print "path '%s' already exists" % path   # overwrite == False and we've hit a directory that exists
                return
        else: raise
    # data making code...
+2

. :

import os, errno

def mkdir(path, overwrite=False):
    try:
        os.makedirs(path)
    except OSError as exc: # Python >2.5
        if exc.errno == errno.EEXIST:
            if not overwrite:
                print "path '%s' already exists" % path   # overwrite == False and we've hit a directory that exists
        else: raise

, else try.

+5
if not os.path.isdir(path):
    os.makedirs(path)
elif not overwrite:
    return # something ?
pass # data making code....

, makedirs . :

try:
    os.makedirs( dir )
except OSError:
    if not overwrite:
        print dir + ' already exists, skipping...'
        return
pass # data making code...

, , , .

0
source

All Articles