在python中递归地创建目录,同时跳过现有目录

2024-09-30 03:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建以下目录:

/autofs/homes/008/gwarner/test1/test2/

/autofs/homes/008/gwarner/test1/test3/

其中/autofs/homes/008/gwarner/已经存在,我没有对所有/autofs/homes/008/的写访问权限。当我试着跑步时:

^{pr2}$

我没有任何输出。在


Tags: 目录权限跑步test1test2test3写访问pr2
2条回答

我想你已经试过了,对吧?也许我误解了你的要求,但你说你想:

Recursively create directories

os.makedirs()的文档以以下内容开头:

Recursive directory creation function.

你可以用os.path.exists模块。在

我会小心点,两者都用操作系统路径.isdir以及os.path.exists在尝试在目录内写入之前检查路径是否为目录,以及os.path.exists在覆盖路径之前。在

例如:

>>> 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,因为它不知道您希望如何处理它。在

是否要覆盖路径(舒蒂尔.rmtree),是要存储路径已设置,还是跳过它?这是由你,编码者,来决定的。在

相关问题 更多 >

    热门问题