在Python中创建目录(复杂)

5 投票
5 回答
8981 浏览
提问于 2025-04-16 00:41

我想创建一堆文件夹和子文件夹,以便可以把文件复制进去。我正在用Python,但找不到一个好的方法来做到这一点。我有一个主路径,然后从这个路径分支出去。接下来,我有“有重量”和“无重量”,然后是“男性”和“女性”。在每个男性和女性的文件夹里,我又有不同的种族(白人、非洲裔美国人、亚洲人、西班牙裔、印度人、其他、未知)。在每个种族的文件夹里,我还有不同的年龄段,从20岁以下到70岁以上(B20、20、30、40、50、60、70)。

我试着生成所有的路径,这样我只需要调用mkdir大约50次,但这差不多要写150行代码。

有没有什么简单的方法可以创建这些文件夹,而不需要手动一个一个去做呢?

5 个回答

2

你只需要像这样做:

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))

这样就能解决你的问题了...

3

这个例子可以帮助你入门:

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

18
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()。只有前者可以在完整路径中创建所有中间的子目录。

撰写回答