【问题标题】:Creating/making directories in python (complex)在 python 中创建/制作目录(复杂)
【发布时间】:2011-03-10 16:35:05
【问题描述】:

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

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

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

【问题讨论】:

  • 您在哪个平台上工作? Python 版本?
  • 好吧,我正在使用带有 Python 2.6 的 Mac...(是的,我知道我仍在使用 Python 2.6,只是因为这个版本和 3 之间发生了重大变化)

标签: python directory mkdir


【解决方案1】:

有几个嵌套的 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 是 os.mkdir

'+'是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

【讨论】:

    【解决方案2】:
    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()。只有前者会构建完整路径中的所有中间子目录。

    【讨论】:

    • 这是个好主意...我从未使用过 itertools,但它的工作原理就像一个魅力,当然它很快!谢谢!
    【解决方案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

    【讨论】:

      【解决方案4】:

      只需这样做:

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

      这应该会为你处理好...

      【讨论】:

        【解决方案5】:

        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
        

        itertools.product 是一种现代而简洁的方法,可以生成所有“A 列中的一个等”选项,以及我在生产软件中的建议——只是:

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

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

        【讨论】:

          猜你喜欢
          • 2018-05-11
          • 2013-08-12
          • 2017-01-02
          • 2017-09-06
          • 2011-03-20
          • 1970-01-01
          • 1970-01-01
          • 2012-11-22
          • 1970-01-01
          相关资源
          最近更新 更多