Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.