4

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
4
  • 1
    Could you post the code so someone can read it? Commented May 31, 2016 at 0:23
  • What's currentpath? Commented May 31, 2016 at 0:34
  • current path is directory: C:\PythonScript Commented May 31, 2016 at 0:50
  • You don't compile under Python. You meant "running does not return any [runtime] error"... Commented Aug 13, 2018 at 23:46

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this!, Just wondering why makedir shows an exception now when it works fine yesterday for the same code.
No worries. It may have been that the subdirectories already existed and you were only creating the timenow dir on the end (which should work).
0

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])

2 Comments

thanks for this but the first IF handles the one inside it dont you think?
If the folder does not exist, create it, then the second if is used to ensure the folder you just created was actually successfully created. Just because you said to create a folder doesn't mean there are not other variables on your system that might cause the folder creation you initiated to fail, like permission issues, full hdd, bad sectors, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.