【发布时间】:2016-12-20 11:41:24
【问题描述】:
创建中间目录和叶目录失败,如以下示例条件(在 MAC OS Darwin 中)。 '/tmp' 目录下有一个 'test' 文件:
if os.path.isfile('/tmp/test'):
if os.path.isdir('/tmp/test') is False:
os.makedirs('/tmp/test')
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-45-71969e2d9a17>", line 3, in <module>
os.makedirs('/tmp/test')
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
mkdir(name, mode)
OSError: [Errno 17] File exists: '/tmp/test'
在这种情况下如何创建目录?
【问题讨论】:
-
您的示例检查文件
/tmp/test是否存在,如果您的示例代码的其余部分运行,则该文件必须返回True。下一个检查是/tmp/test不是一个目录,假设我们知道它是一个文件,它也通过了。然后os.makedirs尝试创建一个目录,其中已经有一个文件。 Python 完全正确地不允许你创建一个已经有文件的目录