3

我有以下代码,os.mkdir不适用于我的。编译不会返回任何错误,但运行代码不会创建文件夹。

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

2 回答 2

5

尝试这个:

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只能创建一个目录。也就是说,你应该看到一个例外。

于 2016-05-31T00:30:31.597 回答
0

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

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])
于 2016-05-31T00:53:55.493 回答