Py:使用嵌套文件夹创建文件夹层次结构

Py: Create a folder hierarchy with nested folders

我正在尝试使用以下内容自动创建项目文件夹结构:

..\Data
..\Data\GPS
..\Data\Tabular
..\Data\Working
..\Documents
..\Documents\Documentation
..\Documents\Pics_Graphics
..\Products

而且,更复杂的是,这就是我所带来的......它......有效......但肯定有一种方法可以将我的层次结构作为列表包含并循环遍历它,同时维护"if exists skip" 条件?我看过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) 

您可以使用 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)