0

我正在尝试用 Python 编写一个递归文件列表程序。当我运行程序而最后没有捕获异常代码时,它返回错误号 5,表示对某些 Windows 文件夹的访问被拒绝。我拥有管理员权限和一切,但它仍然不断向我抛出这个错误。是否有可能解决这个问题并列出这些目录中的文件?

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()
4

1 回答 1

3

os.walk这是一个示例,使用它比尝试自己实现相同的东西要好得多。

例如:

import os

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

至于错误,如果您的权限被拒绝,那么您可能真的被拒绝访问那里。我不是windows用户,所以我不确定,但是您需要以管理员权限运行程序吗?(相当于以root身份运行,或者sudo在linux下运行)。

于 2012-05-05T21:56:46.977 回答