Reputation: 379
I have the below code, the os.mkdir
is not working on mine. Compiling does not return any error, but running the code does not create folder.
def folder():
timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S')
folderpath = os.path.join(currentpath,"folder",str(timenow))
if os.path.exists(folderpath) == False:
os.mkdir(folderpath)
return
Upvotes: 4
Views: 22176
Reputation: 868
Here's my stab at it, with some minor error handling...
def folder():
timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S')
folderpath = os.path.join(os.getcwd(),"folder",str(timenow))
if not os.path.exists(folderpath):
os.makedirs(folderpath)
if os.path.exists(folderpath):
return (True, folderpath)
return (False, folderpath)
f = folder()
if f[0]:
print '"%s" was successfully created!' % (f[1])
else:
print '"%s" could not be created, does the folder already exist? Do you have appropriate permissions to create it?' % (f[1])
Upvotes: 0
Reputation: 8999
Try this:
def folder():
timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S')
folderpath = os.path.join(currentpath, "folder", str(timenow))
if not os.path.exists(folderpath):
os.makedirs(folderpath)
print 'Created:', folderpath
folder()
makedirs
will create the required subdirectories, whereas mkdir
can only create one directory. That said, you should've seen an exception.
Upvotes: 10