使用python

时间:2016-04-08 18:18:41

标签: python directory

如何使用python创建包含多个不同文件夹的多个不同文件夹? 我的路径是:'。/ work / animals /'。 'animals'目录包含文件夹'cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake'和'giraffe' ”。 我已经设法编写了创建所有动物文件夹的部分(下面的代码),但我还想在动物的所有文件夹中创建另外三个子文件夹,即“男性”,“女性”和“未分类”。

import os
root_path = './work/animals/'
folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']

for folder in folders:
     os.mkdir(os.path.join(root_path,folder))

2 个答案:

答案 0 :(得分:1)

您可以使用itertools.product获取所需动物和性别的组合,然后使用os.makedirs为您创建中间目录。

import os
import itertools

root_path = './work/animals/'

folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']
genders = ['male', 'female', 'uncategorized']

for folder,gender in itertools.product(folders, genders):
    os.makedirs(os.path.join(root_path,folder,gender))

答案 1 :(得分:1)

如何简单地做:

import os
root_path = './work/animals/'
folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']
subfolders = ['male', 'female', 'uncategorized']
for folder in folders:
    os.mkdir(os.path.join(root_path,folder))
    for subfolder in subfolders : 
        os.mkdir(os.path.join(root_path,folder,subfolder))