我正在尝试使用以下内容自动创建项目文件夹结构:
..\Data
..\Data\GPS
..\Data\Tabular
..\Data\Working
..\Documents
..\Documents\Documentation
..\Documents\Pics_Graphics
..\Products
而且,过了复杂的事情,这就是我带来的......哪些......工作......但是肯定有一种方法可以将我的层次结构作为一个列表包含并循环通过它同时保持“如果存在跳过“条件?我看过https://codereview.stackexchange.com/questions/28715/script-for-creating-a-hierarchy-of-directories?它具有类似的结果,但在这种情况下我无法解开提供的列表,它基于计数器。
import os
import errno
data = 'C://temp//Pro_Folder_Structure//Data'
try:
os.makedirs(data)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % data)
datagps = 'C://temp//Pro_Folder_Structure//Data//GPS'
try:
os.makedirs(datagps)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % datagps)
dataworking = 'C://temp//Pro_Folder_Structure//Data//Working'
try:
os.makedirs(dataworking)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % dataworking)
datatab = 'C://temp//Pro_Folder_Structure//Data//Tabular'
try:
os.makedirs(datatab)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % datatab)
docs = 'C://temp//Pro_Folder_Structure//Documents'
try:
os.makedirs(docs)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % docs)
document = 'C://temp//Pro_Folder_Structure//Documents//Documentation'
try:
os.makedirs(document)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % document)
pics = 'C://temp//Pro_Folder_Structure//Documents//Pics_Graphics'
try:
os.makedirs(pics)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % pics)
prod = 'C://temp//Pro_Folder_Structure//Products'
try:
os.makedirs(prod)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % prod)
答案 0 :(得分:1)
你可以使用for循环。根据目录的深度,出于实用性原因,您可以使用嵌套的for循环。
所以你可以这么做:
directories = ['Data','GPS','Data//GPS',....,'Products']
basedirectory = 'C://temp//Pro_Folder_Structure//'
for (i in range (len (directories)):
newDir = basedirectory + directories[i]
try:
os.makedirs(newDir)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
else:
print ("\nBE CAREFUL! Directory %s already exists." % newDir)