Inhale.Py
Inhale.Py

Reputation: 260

Search for files by name in multiple directories?

OK so here's my problem. I work out of two directories and all of the sub folders in the directories while at work. I want to write a program that will prompt me for a file name, after the file name is given it will then search these two directories and all sub folders in these directories for any files with matching names. Is there an easy way to do this. Any and all help will be greatly appreciated. I am wanting to do this in python 3 (NOTE: this is my first real project and I honestly have no idea where to begin.)

Upvotes: 2

Views: 4232

Answers (1)

Rushy Panchal
Rushy Panchal

Reputation: 17552

This is a function with a recursive helper function that returns all files in a folder (in dictionary form: {file_name: file_path, ...}.

import os, os.path

def getFiles(path):
    '''Gets all of the files in a directory'''
    sub = os.listdir(path)
    paths = {}
    for p in sub:
        print p # just to see where the function has reached; it's optional
        pDir = os.path.join(path, p)
        if os.path.isdir(pDir): 
            paths.update(getAllFiles(pDir, paths))
        else:
            paths[p] = pDir
    return paths

def getAllFiles(mainPath, paths = {}):
    '''Helper function for getFiles(path)'''
    subPaths = os.listdir(mainPath)
    for path in subPaths:
        pathDir = pDir = os.path.join(mainPath, path)
        if os.path.isdir(pathDir):
            paths.update(getAllFiles(pathDir, paths))
        else:
            paths[path] = pathDir
    return paths

For example, if you were looking for myfile.txt, one of the dictionary key:value pairs would be like {'myfile.txt': 'C:\Users\Example\Path\myfile.txt', ...}.

Depending on how many files a folder has, it may be slow. For searching my sys.path (which has like 10 folders, one of which is Python\Lib, which is massive), it takes about 9 seconds.

Upvotes: 3

Related Questions