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

发布于 2024-09-08 07:52:21 字数 322 浏览 8 评论 0原文

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

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

有没有一种简单的方法可以创建所有这些文件夹而无需手动完成?

I am trying to create a bunch of directories/subdirectories that I can copy files into. I am working with Python and I can't seem to find a good way to do this. I have a main path that I will branch off of. Then after that, I have Weights and No_Weights. Male and Female following. Within each of Male and Female folders, I have each ethnicity (Caucasian, African-American, Asian, Hispanic, Indo, Other, Unknown). Within each of those folders, I have age ranges from Below 20, all the way to 70+ (B20, 20, 30, 40, 50, 60, 70).

I have tried to generate all of the paths so all I would have to call is mkdir about 50 times, but that is about 150 lines of code (almost).

Is there any simple way to create all of these folders without having to do it by hand?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦初启 2024-09-15 07:52:21
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

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() will construct all possible path variations, then os.path.join() will join the subpaths together using the correct syntax for your platform.

EDIT: os.makedirs() is needed instead of os.mkdir(). Only the former will construct all the intermediate subdirectories in a full path.

攒一口袋星星 2024-09-15 07:52:21

这个例子应该可以帮助您入门:

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。产品

This example should get you started:

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)

The itertools module is your friend:
http://docs.python.org/library/itertools.html#itertools.product

℉服软 2024-09-15 07:52:21

只需做这样的事情:

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

这应该会为你解决......

Just do something like this:

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

and that should take care of it for you...

潜移默化 2024-09-15 07:52:21

有几个嵌套的 for 循环,然后每个循环都有 os.mkdir 。使用 os.path.join 将目录路径连接在一起。

像这样的东西:

loop weights
    mkdir weight
    loop sexes
        mkdir weights + sex
        loop ethnicities
            mkdir weights + sex + ethnicity
            loop ages
                mkdir weights + sex + ethnicity + age

这里循环只是一个普通的 for 循环:

for weight in ('weights', 'no_weights'):

mkdir is os.mkdir

'+' is os.path.join:

os.mkdir(os.path.join(weights, sex, ethnicity, age))

编辑: dir_util 可能在这里有用,所以你不必创建每个子目录:

http://docs.python.org/release/2.5。 2/dist/module-distutils.dirutil.html

loop weights
    loop sexes
        loop ethnicities
            loop ages
                mkpath weights + sex + ethnicity + age

Have a few nested for-loops, then os.mkdir for each one. Use os.path.join to concatenate the directory path together.

Something like:

loop weights
    mkdir weight
    loop sexes
        mkdir weights + sex
        loop ethnicities
            mkdir weights + sex + ethnicity
            loop ages
                mkdir weights + sex + ethnicity + age

here loop is just a normal for-loop:

for weight in ('weights', 'no_weights'):

mkdir is os.mkdir

'+' is os.path.join:

os.mkdir(os.path.join(weights, sex, ethnicity, age))

Edit: dir_util might be of some use here so you don't have to make each subdirectory:

http://docs.python.org/release/2.5.2/dist/module-distutils.dirutil.html

loop weights
    loop sexes
        loop ethnicities
            loop ages
                mkpath weights + sex + ethnicity + age
梦里泪两行 2024-09-15 07:52:21

os.makedirs 可以提供帮助 - 它使所有中间目录一直到您指定的“叶”目录。

另一个问题(生成所有“A 列中的一个,B 列中的一个,...”组合)最好作为“混合基数计数”问题来解决 - 粗略地说,s/thing like...:

choices = [ ['Weights', 'Noweights'],
            ['Male', 'Female'],
            ['Caucasian', 'AfricanAmerican', ...
            ...
          ]
Ls = [len(x) for x in choices]
ct = [0] * len(Ls)

while True:
    p = [c[i] for i, c in zip(ct, choices)]
    os.makedirs(os.path.join(p))
    n = -1
    while n > -len(Ls):
      ct[n] += 1
      if ct[n] < Ls[n]: break
      ct[n] = 0
      n -= 1
    else:
      break

< code>itertools.product 是一种现代而简洁的方法,用于生成所有“A 列中的一个,等等”选择,以及我在生产软件中的建议 - 只是:

for p in itertools.product(*choices):
    os.makedirs(os.path.join(p))

可以替换所有上述代码( !)。我认为还值得了解“混合基计数”较低抽象级别的方法,因为它在许多情况下都很方便(包括使用 Python 版本 <2.6;-)。

os.makedirs can help -- it makes all intermediate directories all the way down to the "leaf" one you specify.

The other issue (generating all the "one from column A, one from column B, ..." combinations) is best approached as a problem of "counting in mixed bases" -- roughly, s/thing like...:

choices = [ ['Weights', 'Noweights'],
            ['Male', 'Female'],
            ['Caucasian', 'AfricanAmerican', ...
            ...
          ]
Ls = [len(x) for x in choices]
ct = [0] * len(Ls)

while True:
    p = [c[i] for i, c in zip(ct, choices)]
    os.makedirs(os.path.join(p))
    n = -1
    while n > -len(Ls):
      ct[n] += 1
      if ct[n] < Ls[n]: break
      ct[n] = 0
      n -= 1
    else:
      break

itertools.product is the modern and concise approach to generating all the "one from column A, etc etc" picks, and what I would advise in production software -- just:

for p in itertools.product(*choices):
    os.makedirs(os.path.join(p))

can replace all of the above code (!). I think it's also worth being aware of the "counting in mixed bases" lower-abstraction-level approach because it comes in handy in many cases (including times in which one is stuck using a Python release < 2.6;-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文