我创建了一个Python脚本来在用户目录中创建新文件夹。但是,如果再次运行该程序,它将运行良好,由于某种原因,它将在根目录中创建空白文件夹。例如
根 -戴夫
吉姆
鲍勃
程序运行一次之后
----科学
----英语
----数学
----科学
----英语
----数学
----科学
----英语
----数学
程序再次运行后(以防万一添加了新用户)会发生这种情况
科学
英语
数学
戴夫
----科学
----英语
----数学
----科学
----英语
----数学
----科学
----英语
----数学
如果再次运行该程序,它将起作用。
任何帮助将不胜感激。
Ta
代码在这里:
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)
答案 0 :(得分:0)
在创建具有相同名称的新文件之前,应首先检查目录是否存在。
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
进行写操作会产生意想不到的行为,因此我重命名了变量。