0
votes

I'm trying to write a recursive file listing program in Python. When I run the program without the exception catching code at the end, it returns error number 5, saying that access is denied to some windows folders. I have admin privileges and everything, but it still keeps throwing me this error. Is it at all possible to get around this and list the files in those directories?

import os

def wrapperList():
    mainList = []
    fileList = os.listdir("C:")
    for file in fileList:
        path = os.path.join("C:\\", file)
        if (os.path.isdir(path)):
            mainList.append(recurList(path))
        else:
            mainList.append(path)
    print mainList
def recurList(directory):
    try:
        fileList = os.listdir(directory)
        tempList = []
        for file in fileList:
            path = os.path.join(directory, file)
            if (os.path.isdir(file)):
                tempList.append(recurList(path))
            else:
                tempList.append(file)
        return tempList
    except:
        return ["Access Denied"]

wrapperList()
1
Don't link to your code, post it, also post the exception you get. Edit: Fixed the code by putting it in your post, but you'll need to add the exception.Gareth Latty

1 Answers

3
votes

This is an example where you would be much better off using os.walk than trying to implement the same thing yourself.

E.g:

import os

for root, dirs, files in os.walk("/some/path"):
    ...

As to the error, if you are getting permission denied, then it's probably that you really are denied access there. I'm not a windows user, so I don't know for sure, but do you need to run the program with admin privileges? (equivalent to running as root, or sudo under linux).