python递归创建目录

时间:2022-12-14 12:29:45

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

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


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

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