问题
I have code that makes a folder and places output files in it. I want to use a try-except-else block and an overwrite option, which can be set to True or False, so that in the case where the folder already exists and overwrite is set to false it will just print that the folder already exists, and in all other cases it will just execute without comment.
The only solution I've come up with so far looks like this:
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...
Is there maybe a better, or just more elegant solution to this problem? Like, for example, one in which I don't have to duplicate my data making code? Doing it this way reminds me too much of the style in which I've ended up having to write some things in C, and doesn't seem very Pythonic.
回答1:
(Building on Daniel DiPaolo's answer)
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:
You're pretty close already. Adapting from this answer:
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
I don't see why you'd need an else
on the try
block.
回答3:
if not os.path.isdir(path):
os.makedirs(path)
elif not overwrite:
return # something ?
pass # data making code....
There are reasons why you could want to use makedirs
to test for directory existence. In that case:
try:
os.makedirs( dir )
except OSError:
if not overwrite:
print dir + ' already exists, skipping...'
return
pass # data making code...
You might also want to check if the path exists but is a file and not a directory.
来源:https://stackoverflow.com/questions/4753686/a-more-elegant-way-to-control-overwriting-with-try-except-else-in-python-or-can