<p>可能有一种更优雅的方法来实现这一点,但这应该是有效的:</p>
<pre><code>import os
import itertools
depth = 3
#create the base directory
basepath = '/path/to/alphabet'
os.mkdir(basepath)
#setup alphabet list
#long to crate full directory structure
#alphabet = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'
alphabet = 'A B C' #short alphabet for testing purposes
alphabet = alphabet.split()
#helper variable for determining what depth you are at
c_depth = alphabet
#create depth 0
for letter in alphabet:
#print letter
pth = os.path.join(basepath,letter)
os.mkdir(pth)
#
for d in range(depth-1):
#take the cartesian product of your current directories and your alphabet
#in order to obtain all possible permutations. Will return tuples like
#('AAA','B')
result = list(itertools.product(*(alphabet,c_depth)))
#print d
#reset the current directory list
cdirs = []
#for each directory at the new depth
for elem in result:
#create the full name by joining tuples created previously
dName = ''.join(itertools.chain(elem))
#build up path where it belongs from the letters it is comprised of
pth = basepath
for l in range(len(dName)-1):
pth = os.path.join(pth,dName[:l+1])
#add the new directory folder to the end of the path
pth = os.path.join(pth,dName)
#make new directory
os.mkdir(pth)
#print dName
cdirs.append(dName)
#reset helper variable
c_depth = cdirs
</code></pre>