使用 Python 在用户目录中创建空白文件夹
Using Python to create blank folders in users' directories
我创建了一个 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)
您应该先检查目录是否存在,然后再创建一个新的同名目录。
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 脚本来在用户目录中创建新文件夹。但是它运行良好,如果程序再次为 运行,那么出于某种原因它会在根目录中创建空白文件夹。举个例子
根目录 - 戴夫
吉姆
鲍勃
节目后运行秒一次
- 戴夫
----科学
---- 英文
---- 数学
- 吉姆
----科学
---- 英文
---- 数学
- 鲍勃
----科学
---- 英文
---- 数学
程序再次 运行 后(以防添加新用户)会发生这种情况
科学
英语
数学
戴夫
----科学
---- 英文
---- 数学
- 吉姆
----科学
---- 英文
---- 数学
- 鲍勃
----科学
---- 英文
---- 数学
如果程序是 运行,那么它仍然有效。
如有任何帮助,我们将不胜感激。
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)
您应该先检查目录是否存在,然后再创建一个新的同名目录。
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
会导致意外行为,因此我重命名了该变量。