用python创建/制作目录(复杂)

2024-05-21 04:42:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一堆目录/子目录,可以将文件复制到其中。我正在使用Python,但似乎找不到一个好的方法来实现这一点。我有一条主要的路要开辟。在那之后,我有重量,没有重量。男女跟随。在每个男性和女性文件夹中,我都有各自的种族(白种人、非裔美国人、亚洲人、西班牙裔人、印度群岛人、其他人、未知)。在这些文件夹中,我的年龄从20岁以下一直到70岁以上(B20、20、30、40、50、60、70)。

我已经尝试生成所有路径,所以我只需要调用mkdir大约50次,但这大约是150行代码(几乎)。

有没有什么简单的方法可以创建所有这些文件夹而不必手工操作?


Tags: 文件方法路径目录文件夹重量年龄男性
3条回答

就这样做:

main = 'somedir'
weight = ['weights', 'No_weights']
ethnicity = ['Caucasian', #the rest]
ages = ['B20'] +  range(20, 71, 10)

for w in weights:
    os.mkdir(os.path.join(main, w)
    for e in ethnicity:
        os.mkdir(os.path.join(main, w, e))
        for a in ages:
            os.mkdir(os.path.join(main, w, e, a))

你应该好好照顾它。。。

import itertools
import os

dirs = [["Weights", "No_Weights"],
        ["Male", "Female"],
        ["Caucasian", "African-American", "Asian", "Hispanic", "Indo", "Other", "Unknown"], 
        ["B20", "20", "30", "40", "50", "60", "70"]]

for item in itertools.product(*dirs):
    os.makedirs(os.path.join(*item))

itertools.product()将构造所有可能的路径变体,然后os.path.join()将使用正确的平台语法将子路径连接在一起。

编辑:需要os.makedirs(),而不是os.mkdir()。只有前者才能在完整路径中构造所有中间子目录。

这个例子应该让你开始:

import itertools
import os.path

ROOT = r'C:\base\path'

sex = ('male', 'female')
ethnicity = ('Caucasian', 'African-American', 'Asian')
ages = ('B20', '20', '30')

for path in itertools.product(sex, ethnicity, ages):
    print os.path.join(ROOT, *path)

itertools模块是您的朋友: http://docs.python.org/library/itertools.html#itertools.product

相关问题 更多 >