Recursively go through all directories until you find a certain file in Python
<p>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</p>

<p>startdir = "Users/..../file.txt"</p>

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

<pre><code>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
</code></pre>

<p>Don't re-invent the directory-recursion wheel. Just use the <a href="https://docs.python.org/3/library/os.html#os.walk" rel="nofollow"><code>os.walk()</code> function</a>, which gives you a loop over a recursive traversal of directories:</p>

<pre><code>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
</code></pre>

python file recursion directory