os.mkdir under if not working python

python novice picture python novice · May 31, 2016 · Viewed 10.1k times · Source

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

Answer

101 picture 101 · May 31, 2016

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.