python - 使用Python在用户目录中创建空白文件夹

标签 python directory creation

我创建了一个 Python 脚本来在用户目录中创建新文件夹。然而,它工作得很好,如果再次运行该程序,那么由于某种原因,它会在根目录中创建空白文件夹。举个例子

根 - 戴夫

  • 吉姆

  • 鲍勃

程序运行一次后

  • 戴夫

----科学

---- 英文

----数学

  • 吉姆

----科学

---- 英文

----数学

  • 鲍勃

----科学

---- 英文

----数学

程序再次运行后(以防万一添加新用户)会发生这种情况

  • 科学

  • 英语

  • 数学

  • 戴夫

----科学

---- 英文

----数学

  • 吉姆

----科学

---- 英文

----数学

  • 鲍勃

----科学

---- 英文

----数学

如果程序再次运行,它就可以工作。

如有任何帮助,我们将不胜感激。

代码在这里:

import os

currentPath = os.getcwd()
folders = ["English","Science","Maths"]

directory_list = list()
for root, dirs, files in os.walk(currentPath, topdown=False):
    for name in dirs:
        directory_list.append(os.path.join(root, name))

        path = currentPath+"\\"+name

        for i in range(len(folders)):

            try:  
                os.makedirs(path+"/"+folders[i])
            except OSError:  
                print ("Creation of the directory %s failed" % path)
            else:  
                print ("Successfully created the directory %s " % path)

最佳答案

在创建同名的新目录之前,您应该首先检查该目录是否存在。

import os

currentPath = os.getcwd()
folders = ["English","Science","Maths"]

directory_list = list()
for dir in os.listdir(currentPath):

    temp_path = currentPath+"\\"+dir

    if os.path.isdir(temp_path):
        for folder in folders:
            if not os.path.isdir(temp_path+"\\"+folder):
                new_folder = temp_path+"\\"+folder
                try:
                    os.makedirs(temp_path+"\\"+folder)
                except OSError:  
                    print ("Creation of the directory %s failed" % new_folder)
                else:  
                    print ("Successfully created the directory %s " % new_folder)

我不得不重写一些代码,但我测试了它并且它有效!

我认为写入 var path 会产生意外行为,因此我重命名了该变量。

关于python - 使用Python在用户目录中创建空白文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52760129/

相关文章:

python - download_app 和 coursebuilder 遇到问题

python flask 从 http 重定向到 https

python - 如何在元组列表中连接元组内的元素?

python - reshape numpy 数组的列表,然后 reshape 回来

javascript - rails : Include Javascript_include_tag outside default folders

c - 在 C 中使用通配符枚举目录中的文件

svn - 为什么 subversion 在提交时会切换到父目录

c++ - 制作带参数的命令行程序

sqlite - 黑莓-如何创建SQLite数据库?

c++ - OF_SHARE_DENY_NONE 不分享阅读?