Search code examples
pythonos.path

Python 3: search subdirectories for a file


I'm using Pycharm on a Mac. In the script below I'm calling the os.path.isfile function on a file called dwnld.py. It prints out "File exists" since dwnld.py is in the same directory of the script (/Users/BobSpanks/PycharmProjects/my scripts). If I was to put dwnld.py in a different location, how to make the code below search all subdirectories starting from /Users/BobbySpanks for dwnld.py? I tried reading os.path notes but I couldn't really find what I needed. I'm new to Python.

import os.path

File = "dwnld.py"

if os.path.isfile(File):
    print("File exists")
else:
    print("File doesn't exist")

Solution

  • This might work for you:

    import os
    File = 'dwnld.py'
    for root, dirs, files in os.walk('/Users/BobbySpanks/'):  
        if File in files:
            print ("File exists")
    

    os.walk(top, topdown=True, onerror=None, followlinks=False)

    Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). Source