python递归创建目录

os.mkdir()可以创建指定的目录,但如果其上一级目录不存在,则无法创建成功。

os.makedirs()则可以实现递归创建目录的功能。


下面的代码实现了os.makedirs()类似的功能,——事实上在实现这个功能的时候,还不清楚有makedirs()这个库函数尴尬,所以多看看书,扩大知识面非常有必要,避免闭门造车,做无用功。

def mkdir_recursively(path):
    '''
    Create the path recursively, same as os.makedirs().
    
    Return True if success, or return False.
    
    e.g.
    mkdir_recursively('d:\\a\\b\\c') will create the d:\\a, d:\\a\\b, and d:\\a\\b\\c if these paths does not exist.
    '''
    
    #First transform '\\' to '/'
    local_path = path.replace('\\', '/')
    
    path_list = local_path.split('/')
    print path_list 
    
    if path_list is None: return False 
    
    # For windows, we should add the '\\' at the end of disk name. e.g. C: -> C:\\
    disk_name = path_list[0]
    if disk_name[-1] == ':': path_list[0] = path_list[0] + '\\'
    
    dir = ''
    for path_item in path_list:
        dir = os.path.join(dir, path_item)
        print "dir:", dir 
        if os.path.exists(dir):
            if os.path.isdir(dir):
                print "mkdir skipped: %s, already exist." % (dir,)
            else: # Maybe a regular file, symlink, etc.
                print "Invalid directory already exist:", dir 
                return False
        else:
            try:
                os.mkdir(dir)
            except Exception, e:
                print "mkdir error: ", dir
                print e 
                return False 
            print "mkdir ok:", dir
    return True 

示例:

>>> import os
>>> dir = "d:\\x\\y\\z"
>>> os.mkdir(dir)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
WindowsError: [Error 3] : 'd:\\x\\y\\z'
>>> import file_utilities
>>> file_utilities.mkdir_recursively(dir)
['d:', 'x', 'y', 'z']
dir: d:\
mkdir skipped: d:\, already exist.
dir: d:\x
mkdir ok: d:\x
dir: d:\x\y
mkdir ok: d:\x\y
dir: d:\x\y\z
mkdir ok: d:\x\y\z
True
>>> os.makedirs("d:\\xx\\yy\\zz")
>>>

下面是Python 2.7中os.py的实现代码:

def makedirs(name, mode=0777):
    """makedirs(path [, mode=0777])

    Super-mkdir; create a leaf directory and all intermediate ones.
    Works like mkdir, except that any intermediate path segment (not
    just the rightmost) will be created if it does not exist.  This is
    recursive.

    """
    head, tail = path.split(name)
    if not tail:
        head, tail = path.split(head)
    if head and tail and not path.exists(head):
        try:
            makedirs(head, mode)
        except OSError, e:
            # be happy if someone already created the path
            if e.errno != errno.EEXIST:
                raise
        if tail == curdir:           # xxx/newdir/. exists if xxx/newdir exists
            return
    mkdir(name, mode)

通过对比,发现一个新的方法:os.path.split(),专门用来对文件的路径进行分割。从而避免调用string.split(),且区分/和\。再者,os.makedirs()通过递归调用来创建目录,对路径的构造更加灵活,且直接从后往前判断路径是否存在,效率会高一些。

os.path.split()的用法示例:

>>> import os
>>> dir = "d:\\xxx\\\yyy\\\zzz"
>>> head,tail=os.path.split(dir)
>>> head
'd:\\xxx\\\\yyy'
>>> tail
'zzz'
>>>



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值