Python os.listdir在某些文件夹上抛出“WindowsError: [Error 5] 访问被拒绝:”

1 投票
2 回答
5948 浏览
提问于 2025-04-17 14:49

基本上,我有一个用Python 2.6写的文件浏览器类。它运行得很好,我可以在驱动器、文件夹之间自由浏览。

但是,当我进入一个特定的文件夹 'C:\Documents and Settings/.*'*, 我用来列出文件的os.listdir就报错了:

WindowsError: [Error 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

2 个回答

0

这可能是因为你没有权限访问这个文件夹,或者这个文件夹根本就不存在。你可以尝试以管理员身份运行你的脚本(这样就可以访问所有内容),或者试试下面这个方法:

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 吗?这个方法可能是你想要实现的功能的一个快捷方式。

3

在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中处理符号链接的回答。

撰写回答