递归遍历所有目录,直到在Python中找到某个文件 [英] Recursively go through all directories until you find a certain file in Python

查看:408
本文介绍了递归遍历所有目录,直到在Python中找到某个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中递归地遍历所有目录直到找到特定文件的最佳方法是什么?
我想浏览目录中的所有文件,并查看我要查找的文件是否在该目录中。
如果找不到,请转到父目录并重复该过程。我还想计算
找到文件之前要经过的目录和文件数。如果循环的
末尾没有文件,则返回没有文件

What's the best way in Python to recursively go through all directories until you find a certain file? I want to look through all the files in my directory and see if the file I'm looking for is in that directory. If I cannot find it, I go to the parent directory and repeat the process. I also want to count how many directories and files I go through before I find the file. If there is no file at the end of the loop return that there is no file

startdir = Users /..../ file.txt

startdir = "Users/..../file.txt"

findfile是文件名。这是我当前的循环,但是我想使用递归来使其工作。

findfile is name of file. This is my current loop but I want to make it work using recursion.

def walkfs(startdir, findfile):
    curdir = startdir
    dircnt = 0
    filecnt = 0
    for directory in startdir:
        for file in directory:
            curdir = file
            if os.path.join(file)==findfile:
                return (dircnt, filecnt, curdir)
            else:
                dircnt+=1
                filecnt+=1


推荐答案

不要重新发明目录递归轮。只需使用 os.walk()函数,它使您可以循环遍历目录:

Don't re-invent the directory-recursion wheel. Just use the os.walk() function, which gives you a loop over a recursive traversal of directories:

def walkfs(startdir, findfile):
    dircount = 0
    filecount = 0
    for root, dirs, files in os.walk(startdir):
        if findfile in files:
            return dircount, filecount + files.index(findfile), os.path.join(root, findfile)
        dircount += 1
        filecount += len(files)
    # nothing found, return None instead of a full path for the file
    return dircount, filecount, None

这篇关于递归遍历所有目录,直到在Python中找到某个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆