尝试递归查找文件夹时出现错误5

2024-10-03 04:25:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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()

Tags: 文件path程序osdef错误directoryfile
1条回答
网友
1楼 · 发布于 2024-10-03 04:25:45

在这个例子中,使用^{}比自己尝试实现同样的东西要好得多。你知道吗

例如:

import os

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

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

相关问题 更多 >