【问题标题】:os.makedirs generates exception when a file exists with the same name in Python 2.7.10os.makedirs 在 Python 2.7.10 中存在同名文件时生成异常
【发布时间】: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 完全正确地不允许你创建一个已经有文件的目录

标签: python darwin os.path


【解决方案1】:

如果要创建临时目录,请使用tempfile.mkdtemp()

【讨论】:

    【解决方案2】:

    正如 Simon Walker 所说,这不是 Python 中的错误或实现错误。操作系统(不仅是 Darwin,还有其他操作系统,如 Windows)不允许在目录中拥有同名的文件和目录。对于 Unix/Linux,请参阅 explanation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-16
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2013-03-29
      • 2011-03-04
      相关资源
      最近更新 更多