Python search for single filename recursively in directory tree. Return false if not found
<p>Using Python, I would like to search a directory tree recursively for a specific file name.</p>

<p>**If found, print nothing.</p>

<p>**If not found print a message stating it was not found.</p>

<p>===== here is what I have so far, no errors, but no message when file not found either=====</p>

<pre><code>import os
rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
def find_file(file_name,rootDir):
    for dirpath, dirnames, filenames in os.walk(rootDir):
        if file_name in filenames:
            print 'found'
</code></pre>

<p>Return early when you find the file; that way, after your <code>os.walk()</code> loop has completed you know the file was never found:</p>

<pre><code>import os

def find_file(name, root):
    for _, _, filenames in os.walk(root):
        if name in filenames:
            return  # found the file, exit early
    print 'Not found'

rootDir = 'G:\\some_top_directory\\'
file_name = 'fileOFinterest.txt'
find_file(file_name, rootDir)
</code></pre>

<p>I used <code>_</code> for both the dirpath and directories values returned by <code>os.walk()</code> for each iteration; the loop otherwise ignores these and <code>_</code> signals this to the reader.</p>

python recursion filenames os.walk