【问题标题】:Python os.listDir throws "WindowsError: [Error 5] Access is denied:" on some foldersPython os.listDir 在某些文件夹上抛出“WindowsError:[错误 5] 访问被拒绝:”
【发布时间】:2013-01-20 13:36:59
【问题描述】:

基本上我有一个用 Python 2.6 编写的 FileExplorer 类。效果很好,我可以浏览驱动器、文件夹等。 但是,当我到达特定文件夹 'C:\Documents and Settings/.*'*,我的脚本所基于的 os.listdir 会引发此错误:

WindowsError:[错误 5] 访问被拒绝:'C:\Documents and Settings/.'

这是为什么呢?是因为这个文件夹是只读的吗?还是 Windows 正在保护的东西而我的脚本无法访问?!

这是有问题的代码(第 3 行):

def listChildDirs(self):
    list = []
    for item in os.listdir(self.path):
        if item!=None and\
            os.path.isdir(os.path.join(self.path, item)):
            print item
            list.append(item)
        #endif
    #endfor
    return list

【问题讨论】:

  • 哪个版本的 Windows?在 Vista 及更高版本中,C:\Documents and Settings 是一个联结,而不是一个真正的目录。
  • 这是 Windows 7,抱歉忘了说。

标签: python windows file operating-system


【解决方案1】:

在 Vista 及更高版本中,C:\Documents and Settings 是一个连接点,而不是一个真正的目录。

你甚至不能在里面直接写dir

C:\Windows\System32>dir "c:\Documents and Settings"
 Volume in drive C is OS
 Volume Serial Number is 762E-5F95

 Directory of c:\Documents and Settings

File Not Found

可悲的是,使用os.path.isdir(),它将返回True

>>> import os
>>> os.path.isdir(r'C:\Documents and Settings')
True

您可以查看这些在 Windows 中处理符号链接的答案。

【讨论】:

  • 正是我的想法。这对异常处理很有用。
  • 非常感谢,这解释了很多。 @Mike,是的,正是我正在考虑如何解决它 - 捕获异常。
【解决方案2】:

这可能是目录访问的权限设置,甚至目录不存在。您可以以管理员身份运行脚本(即访问所有内容)或尝试以下操作:

def listChildDirs(self):
    list = []
    if not os.path.isdir(self.path):
        print "%s is not a real directory!" % self.path
        return list
    try:
        for item in os.listdir(self.path):
            if item!=None and\
                os.path.isdir(os.path.join(self.path, item)):
                print item
                list.append(item)
            #endif
        #endfor
    except WindowsError:
        print "Oops - we're not allowed to list %s" % self.path
    return list

对了,你听说过os.walk吗?看起来这可能是您要实现的目标的捷径。

【讨论】:

  • os.walk 不会递归地列出所有目录的子、孙、孙子等吗?我只想给孩子们看。
  • 你可以通过在for循环中返回来停止行走
猜你喜欢
  • 2011-03-01
  • 1970-01-01
  • 2013-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
相关资源
最近更新 更多