os.mkdir 如果不工作 python

os.mkdir under if not working python

我有以下代码,os.mkdir 在我的代码中不起作用。编译没有return任何错误,但是运行代码没有创建文件夹。

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

试试这个:

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 将创建所需的子目录,而 mkdir 只能创建一个目录。也就是说,您应该已经看到了异常。

这是我的尝试,有一些小错误处理...

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