我正在尝试创建以下目录:
/autofs/homes/008/gwarner/test1/test2/
/autofs/homes/008/gwarner/test1/test3/
/autofs/homes/008/gwarner/
已经存在的地方,我没有/autofs/homes/008/
所有人的写入权限.当我尝试跑步时:
dir = '/autofs/homes/008/gwarner/test/test1/test4/test5/'
for root, dirs, files in os.walk(dir, topdown = True):
print root
我根本没有输出。
我想你已经尝试过os.makedirs()
了,对吧? 也许我误解了你的要求,但你说你想:
递归创建目录
os.makedirs()
的文档开头为:
递归目录创建函数。
您可以使用 os.path.exists 模块。
我会小心并使用os.path.isdir和os.path.exist来检查路径是否是目录,然后再尝试写入目录,并且在覆盖路径之前使用os.path.exist。
例如:
>>> import os
>>> os.path.isdir('/home')
True
>>> os.path.isdir('/usr/bin')
True
>>> os.path.isdir('/usr/bin/python')
False
# writing a single, non-recursive path
>>> if not os.path.exists('/home/cinnamon'):
... os.mkdir('/home/cinnamon')
# writing a single, recursive path
>>> if not os.path.exists('/home/alex/is/making/a/really/long/path'):
... os.makedirs('/home/alex/is/making/a/really/long/path')
# now to script the latter
>>> paths = ['/home/alex/path/one', ...]
>>> for path in paths:
>>> if not os.path.exists(path):
>>> os.makedirs(path)
这样,您就不会覆盖任何存在的内容,而是在写入目录之前检查某些内容是否是目录。根据设计,如果路径存在,系统会抛出 OSError ,因为它不知道您要如何处理它。
是要覆盖路径(shutil.rmtree),是要存储已设置的路径,还是要跳过它?这是由您(编码人员)决定的。