Philip Kroup
Philip Kroup

Reputation: 47

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")

Upvotes: 3

Views: 15078

Answers (5)

HeheBoi420
HeheBoi420

Reputation: 3

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")

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168886

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

Upvotes: 6

Mike Müller
Mike Müller

Reputation: 85622

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.

Upvotes: 6

Telefonmann
Telefonmann

Reputation: 315

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

Upvotes: 3

appills
appills

Reputation: 302

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 

Upvotes: -1

Related Questions