Skip to content

Instantly share code, notes, and snippets.

@msafadieh
Created December 18, 2018 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msafadieh/269e2c3a6d44444a58f9c786a7ed6797 to your computer and use it in GitHub Desktop.
Save msafadieh/269e2c3a6d44444a58f9c786a7ed6797 to your computer and use it in GitHub Desktop.
python recursive directory search
#! /bin/python3
'''
A little script that searches through folders for me and prints any files/dirs
that contain the query in the filename.
This is what happens when you don't really feel like going through the man of
the find command.
usage:
python3 find_query.py [query] [path]
example:
python3 find_query cs101 ~/Documents
'''
from os import listdir
from os.path import isdir, join
from sys import argv
def find_query(query, folder):
"""
iterates through every file in dir and prints matches.
makes recursive call if file is a dir.
"""
if not isdir(folder):
exit(f"Error: {folder} is not a folder")
subdirs = []
for file in listdir(folder):
full_path = join(folder, file)
if query in file:
print(full_path)
if isdir(full_path):
subdirs.append(file)
for subdir in subdirs:
find_query(query, join(folder, subdir))
if __name__ == "__main__":
if len(argv) < 3:
exit("Usage: find_query.py [query] [path]")
find_query(argv[1], argv[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment