Python 3: search subdirectories for a file

Question:

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")
Asked By: Philip Kroup

||

Answers:

Try this

import os
File = "dwnld.py"

for root, dirs, files in os.walk('.'):
    for file in files: # loops through directories and files
        if file == File: # compares to your specified conditions
            print ("File exists")

Taken from: https://stackoverflow.com/a/31621120/5135450

Answered By: Telefonmann

something like this, using os.listdir(dir):

import os
my_dirs = os.listdir(os.getcwd())
for dirs in my_dirs:
    if os.path.isdir(dirs):
        os.chdir(os.path.join(os.getcwd(), dirs)
        #do even more 
Answered By: appills

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

Answered By: Robᵩ

You can use the glob module for this:

import glob
import os

pattern = '/Users/BobbySpanks/**/dwnld.py'

for fname in glob.glob(pattern, recursive=True):
    if os.path.isfile(fname):
        print(fname)

A simplified version without checking if dwnld.py is actually file:

for fname in glob.glob(pattern, recursive=True):
    print(fname)

Theoretically, it could be a directory now.

If recursive is true, the pattern '**' will match any files and zero
or more directories and subdirectories.

Answered By: Mike Müller

You may also use the Path module built into python and use the glob method of that

Code for that:-

import Path
File = "dwnld.py"

pattern = '/Users/BobbySpanks/**/dwnld.py'

for fname in Path(pattern.rstrip(File)).glob(File, recursive=True):
    if os.path.isfile(fname):
        print("File exists")
    else:
        print("File doesn't exist")
Answered By: Viswas
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.