【问题标题】:python: why does os.makedirs cause WindowsError?python: 为什么 os.makedirs 会导致 WindowsError?
【发布时间】:2013-07-12 16:00:01
【问题描述】:

在python中,如果不存在,我已经创建了一个创建目录的函数。

def make_directory_if_not_exists(path):
    try:
        os.makedirs(path)
        break    
    except OSError as exception:
        if exception.errno != errno.EEXIST:
            raise

在 Windows 上,有时我会得到以下异常:

WindowsError: [Error 5] Access is denied: 'C:\\...\\my_path'

在 Windows 文件浏览器中打开目录时似乎会发生这种情况,但我无法可靠地重现它。所以我只是做了以下解决方法。

def make_directory_if_not_exists(path):
    while not os.path.isdir(path):
        try:
            os.makedirs(path)
            break    
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
        except WindowsError:
            print "got WindowsError"
            pass       

这里发生了什么,即 Windows mkdir 何时给出这样的访问错误?有没有更好的解决方案?

【问题讨论】:

  • 来自docsRaises an error exception if the leaf directory already exists or cannot be created.
  • @AshwiniChaudhary,我知道。我已经用except OSError 捕捉到了这个异常。我在问WindowsError

标签: python windows


【解决方案1】:

您应该使用 OSError 和 IOError。请参阅this 答案,您将使用类似:

  def make_directory_if_not_exists(path):
    try:
        os.makedirs(path)
    except (IOError, OSError) as exception:
        if exception.errno != errno.EEXIST:
           ...

【讨论】:

    【解决方案2】:

    稍微搜索一下就会发现这个错误是在各种不同的上下文中引发的,但其中大多数都与权限错误有关。该脚本可能需要以管理员身份运行,或者可能有另一个程序正在使用您尝试使用的目录之一打开。

    【讨论】:

      【解决方案3】:

      关于您关于更好解决方案的问题,我将在这里使用简单明了的三行代码:

      def make_directory_if_not_exists(path):
          if not os.path.isdir(path):
              os.makedirs(path)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-23
        • 2023-03-05
        • 2011-01-03
        • 1970-01-01
        • 2012-06-11
        • 2013-02-25
        • 2012-12-31
        • 2014-01-01
        相关资源
        最近更新 更多