简体   繁体   English

在Python中递归搜索文件

[英]Recursively searching for files in Python

I am trying to write code that uses a recursive function to search for files in a directory, and returns the path to the file that matches the search term. 我正在尝试编写使用递归函数在目录中搜索文件的代码,并返回与搜索词匹配的文件的路径。 However, I keep getting this error when I use "../.." as the path name "PermissionError: [WinError 5] Access is denied: '../..\\AppData\\Local\\Application Data'". 但是,当我使用“ ../ ..”作为路径名“ PermissionError:[WinError 5]访问被拒绝:'../ .. \\ AppData \\ Local \\ Application Data'”时,我一直收到此错误。

import os
def main():

pathname=input('Please enter path name: ')
filenameinput=input('Please enter file name: ')

def disk_usage(path):

    if os.path.isdir(path):
        for filename in os.listdir(path):
            childpath = os.path.join(path, filename)
            if os.path.isdir(childpath):
                disk_usage(childpath)
            else:
                if childpath.endswith(filenameinput):
                    print(childpath)
#return 
disk_usage(pathname)
main()

I should not need to use os.walk() for this. 我不需要为此使用os.walk() I have it working but it returns several paths ending in the filename I specified and then returns the WinError 5 thing. 我可以使用它,但是它返回以我指定的文件名结尾的几个路径,然后返回WinError 5。

You're getting a permission error because Application Data is not a real folder in Windows 7+, it's a "junction" (symlink in Unix-speak) pointing to C:\\Program Files . 您收到权限错误,因为Application Data在Windows 7+中不是真实的文件夹,它是指向C:\\Program Files的“连接”(Unix中的符号链接)。 It only exists for backwards compatibility. 仅为了向后兼容而存在。

You have two options: 您有两种选择:

  1. You can read the junction with some Windows-specific native code, through win32file . 您可以通过win32file读取带有某些Windows特定本机代码的win32file See this SO answer. 看到这个答案。

  2. You can catch the permission error, and ignore it (maybe print a warning message). 您可以捕获到权限错误,然后将其忽略(可能会显示警告消息)。 This is probably the better option unless you really need to read this folder. 除非您确实需要阅读此文件夹,否则这可能是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM