Below are two versions of the same create_dir
function that creates a directory from a file path supplied as file_path
argument.
The Version A checks if there is a directory in the supplied as a function argument file_path
and only then tries to create a directory. The second Version B skips the extra check and feeds the output of the os.path.dirname(file_path)
command straight into the os.makedir
. Also, please note, that there are three if
statements used in Version A, while version B doesn't have any.
Which version A or B is more preferred or more Pythonic?
Version A:
def create_dir(file_path):
dirname = None
os_dirname = None
if file_path:
dirname = os.path.dirname(file_path)
if dirname:
os_dirname = dirname
if os_dirname:
try:
os.makedirs(os_dirname)
except OSError as e:
if e.errno != errno.EEXIST:
raise
Version B
def create_dir(file_path):
try:
os.makedirs(os.path.dirname(file_path))
except Exception as e:
if e.errno != errno.EEXIST:
raise(e)