创建递归路径Python的有效方法

时间:2009-06-03 12:46:08

标签: python path operating-system

我需要一个简单的函数来在Python中创建一个父级可能存在或不存在的路径。

如果其中一个父项存在,os.makedirs将从python文档中失败。

我已经编写了下面的方法,可以根据需要创建多个子目录。

这看起来效率如何?

def create_path(path):
    import os.path as os_path
    paths_to_create = []
    while not os_path.lexists(path):
        paths_to_create.insert(0, path)
        head,tail = os_path.split(path)
        if len(tail.strip())==0: # Just incase path ends with a / or \
            path = head
            head,tail = os_path.split(path)
        path = head

    for path in paths_to_create:
        os.mkdir(path)

8 个答案:

答案 0 :(得分:48)

  

“如果其中一个父项存在,则来自python文档os.makedirs将失败。”

不,如果目录本身已存在,os.makedirs将失败。如果任何父目录已经存在,它将不会失败。

答案 1 :(得分:16)

这是我的看法,它让系统库可以完成所有的路径争用。传播除现有目录以外的任何错误。

import os, errno

def ensure_dir(dirname):
    """
    Ensure that a named directory exists; if it does not, attempt to create it.
    """
    try:
        os.makedirs(dirname)
    except OSError, e:
        if e.errno != errno.EEXIST:
            raise

答案 2 :(得分:4)

草稿:

import os


class Path(str):
    """
    A helper class that allows easy contactenation
    of path components, creation of directory trees,
    amongst other things.
    """  
    @property
    def isdir(self):
        return os.path.isdir(self)

    @property
    def isfile(self):
        return os.path.isfile(self)

    def exists(self):
        exists = False
        if self.isfile:
            try:
                f = open(self)
                f.close()
                exists = True
            except IOError:
                exists = False
        else:
            return self.isdir
        return exists

    def mktree(self, dirname):
        """Create a directory tree in this directory."""
        newdir = self + dirname
        if newdir.exists():
            return newdir
        path = dirname.split('/') or [dirname]
        current_path = self + path.pop(0)
        while True:
            try:
                os.mkdir(current_path)
            except OSError as e:
                if not e.args[0] == 17:
                    raise e
                current_path = current_path + path.pop(0)
                continue
            if len(path) == 0:
                break
        return current_path

    def up(self):
        """
        Return a new Path object set a the parent
        directory of the current instance.
        """
        return Path('/'.join(self.split('/')[:-1]))

    def __repr__(self):
        return "<Path: {0}>".format(self)

    def __add__(x, y):
        return Path(x.rstrip('/') + '/' + y.lstrip('/'))

答案 3 :(得分:3)

使用python(&gt; = 3.4.1),os.makedirs有exists_ok参数。

  

如果exist_ok为False(默认值),则在目标时引发OSError   目录已经存在。

因此,如果您使用like exist_ok = True,那么创建递归目录就不会有任何问题。

  

注意:另一方面,exists_ok附带python 3.2有一个bug   关于提高异常,即使你设置为True。所以尝试使用python&gt; =   3.4.1(在该版本中修复)

答案 4 :(得分:2)

尝试此代码,它检查路径是否存在,直到n子目录级别,并创建目录(如果不存在)。

def pathtodir(path):
if not os.path.exists(path):
    l=[]
    p = "/"
    l = path.split("/")
    i = 1
    while i < len(l):
        p = p + l[i] + "/"
        i = i + 1
        if not os.path.exists(p):
            os.mkdir(p, 0755)

答案 5 :(得分:1)

我在研究在项目目录中创建简单目录树的方法时发现了这个问题。

我对Python有些新意,当数据结构过于复杂(即嵌套)时,我很难过。我的大脑的心理映射更容易跟踪小的迭代列表,所以我提出了两个非常基本的def来帮助我创建目录树。

该示例需要四个对象来创建树:

  1. 根目录路径= PROJECT_HOME
  2. 主路径=主页(如果不存在则创建,不会被覆盖)
  3. 一个可迭代的目录名称,它们将进入home = branches(在home中创建,不会被覆盖)
  4. 映射到branches = leaves的键控迭代字典(每个映射分支内创建的每个值,不会被覆盖)
  5. 如果存在任何目录,则不会覆盖该目录,并且错误会以无提示方式传递。

    import os
    from os.path import join as path_join
    import errno
    
    def make_node(node):
        try:
            os.makedirs(node)
        except OSError, e:
            if e.errno != errno.EEXIST:
                raise
    
    
    def create_tree(home, branches, leaves):
        for branch in branches:
            parent = path_join(home, branch)
            make_node(parent)
            children = leaves.get(branch, [])
            for child in children:
                child = os.path.join(parent, child)
                make_node(child)
    
    if __name__ == "__main__":
        try:  # create inside of PROJECT_HOME if it exists
            PROJECT_HOME = os.environ['PROJECT_HOME']
        except KeyError:  # otherwise in user's home directory
            PROJECT_HOME = os.expanduser('~')
    
        home = os.path.join(PROJECT_HOME, 'test_directory_tree')
        create_tree(home, branches=[], leaves={})
    
        branches = (
            'docs',
            'scripts',
        )
        leaves = (
            ('rst', 'html', ),
            ('python', 'bash', )
        )
        leaves = dict(list(zip(branches, leaves)))
        create_tree(home, branches, leaves)
    
        python_home = os.path.join(home, 'scripts', 'python')
        branches = (
            'os',
            'sys',
            'text_processing',
        )
        leaves = {}
        leaves = dict(list(zip(branches, leaves)))
        create_tree(python_home, branches, leaves)
    
        after_thought_home = os.path.join(home, 'docs', 'after_thought')
        branches = (
            'child_0',
            'child_1',
        )
        leaves = (
            ('sub_0', 'sub_1'),
            (),
        )
        leaves = dict(list(zip(branches, leaves)))
        create_tree(after_thought_home, branches, leaves)
    
  6. 此示例创建的目录树如下所示:

        dev/test_directory_tree/
        ├── docs
        │   ├── after_thought
        │   │   ├── child_0
        │   │   │   ├── sub_0
        │   │   │   └── sub_1
        │   │   └── child_1
        │   ├── html
        │   └── rst
        └── scripts
            ├── bash
            └── python
                ├── os
                ├── sys
                └── text_processing
    

答案 6 :(得分:1)

This code将使用递归函数调用生成具有给定深度和宽度的目录树:

#!/usr/bin/python2.6

import sys
import os

def build_dir_tree(base, depth, width):
    print("Call #%d" % depth)
    if depth >= 0:
        curr_depth = depth
        depth -= 1
        for i in xrange(width):
                # first creating all folder at current depth
                os.makedirs('%s/Dir_#%d_level_%d' % (base, i, curr_depth))
        dirs = os.walk(base).next()[1]
        for dir in dirs:
                newbase = os.path.join(base,dir)
                build_dir_tree(newbase, depth, width)
    else:
        return

if not sys.argv[1:]:
        print('No base path given')
        sys.exit(1)

print('path: %s, depth: %d, width: %d' % (sys.argv[1], int(sys.argv[2]), int(sys.argv[3])))
build_dir_tree(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]))

答案 7 :(得分:1)

这是一个老线程,但我对所提供的解决方案并不满意,因为它们对于简单的任务而言过于复杂。

从库中的可用功能来看,我认为最干净的是:

os.path.isdir("mydir") or os.makedirs("mydir")