1

Basically I have a FileExplorer class written in Python 2.6. It works great, I can navigate through drives, folders, etc. However, when I get to a specific folder 'C:\Documents and Settings/.*'*, os.listdir, on which my script is based, throws this error:

WindowsError: [Error 5] Access is denied: 'C:\Documents and Settings/.'

Why is that? Is it because this folder is read-only? Or is it something Windows is protecting and my script cannot access?!

Here is the offending code(line 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
Radu
  • 2,076
  • 2
  • 20
  • 40

2 Answers2

3

In Vista and later, C:\Documents and Settings is a junction, not a real directory.

You can't even do a straight dir in it.

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

Sadly, using os.path.isdir(), it will return True

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

You could have a look at these answers for dealing with symlinks in Windows.

Community
  • 1
  • 1
Rod
  • 52,748
  • 3
  • 38
  • 55
  • Exactly what I was thinking. This is a good use for exception handling. – Mike Feb 05 '13 at 15:41
  • Thank you very much, this explains a lot. @Mike, yes, exactly how I'm thinking of working around it - catch the exception. – Radu Feb 06 '13 at 07:31
0

It's probably a permissions setting for directory access, or even that the directory's not there. You can either run your script as administrator (ie access to everything) or try something like this:

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

By the way, have you heard of os.walk? It looks like it might be a short cut for what you're trying to achieve.

danodonovan
  • 19,636
  • 10
  • 70
  • 78
  • Wouldn't os.walk just recursively list all the directory's children, grandchildren, grand-grand children, etc? I want to just show the children. – Radu Feb 06 '13 at 07:30
  • You could stop walking by returning in the `for` loop – Rod Feb 06 '13 at 14:39