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

16 投票
8 回答
38879 浏览
提问于 2025-04-15 12:01

我需要一个简单的函数,用来在Python中创建一个路径,这个路径的上级目录可能存在,也可能不存在。

根据Python的文档,如果上级目录已经存在,os.makedirs这个方法就会失败。

我写了下面这个方法,它可以根据需要创建尽可能多的子目录。

这样做效率怎么样?

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 个回答

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('/'))
17

这是我的看法,让系统库来处理所有的路径问题。除了目录已经存在以外的任何错误都会被传递出来。

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
48

“根据Python的文档,os.makedirs 如果有一个父目录存在就会失败。”

其实不是这样的,os.makedirs 只有在你要创建的目录本身已经存在时才会失败。如果只是某个父目录已经存在,它是不会失败的。

撰写回答