Python os.listDir抛出;WindowsError:[错误5]访问被拒绝:";在一些文件夹上
基本上我有一个用Python 2.6编写的FileExplorer类。它工作得很好,我可以浏览驱动器、文件夹等。 但是,当我进入特定文件夹“C:\Documents and Settings/*”时,脚本所基于的os.listdir会抛出以下错误: WindowsError:[错误5]访问被拒绝:“C:\Documents and Settings/” 为什么呢?是因为此文件夹是只读的吗?还是Windows正在保护而我的脚本无法访问 以下是违规代码(第3行):Python os.listDir抛出;WindowsError:[错误5]访问被拒绝:";在一些文件夹上,python,windows,file,operating-system,Python,Windows,File,Operating System,基本上我有一个用Python 2.6编写的FileExplorer类。它工作得很好,我可以浏览驱动器、文件夹等。 但是,当我进入特定文件夹“C:\Documents and Settings/*”时,脚本所基于的os.listdir会抛出以下错误: WindowsError:[错误5]访问被拒绝:“C:\Documents and Settings/” 为什么呢?是因为此文件夹是只读的吗?还是Windows正在保护而我的脚本无法访问 以下是违规代码(第3行): 这可能是目录访问的权限设置,甚至可
这可能是目录访问的权限设置,甚至可能是目录不存在。您可以以管理员身份运行脚本(即访问所有内容),也可以尝试以下操作:
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
顺便问一下,你听说过吗?看起来这可能是实现目标的捷径。在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中处理符号链接的答案
for
循环来停止行走
>>> import os
>>> os.path.isdir(r'C:\Documents and Settings')
True