Writing recursion functions

Hello folks, question regarding recursions.

I had to write a function that recursively searches the root directory for a file name with the specified keyword.

My best attempt to solve this task below, I would like to know how this function can be further optimized? I would appreciate your input.

There’s a directory named 46-subdirs. That directory contains other directories inside. Please write a script that counts the number of .py files contained inside subdirs and all its sub-directories.

import os

dir = “46-subdirs/”

def find(root_path, keyword):

def dir_checker(path, keyword):

contents_list = os.listdir(path)

dir_list = []

file_list = []

for item in contents_list:

  if os.path.isfile(path + item) == False:

    dir_list.append(path + item + "/")

  if os.path.isfile(path + item) == True and item.__contains__(keyword):




if len(dir_list) > 0:

  for dir in dir_list:

    return len(file_list) + dir_checker(dir, keyword)

return len(file_list)

root_dir_list = os.listdir(root_path)

rez_count = 0

for dir_item in root_dir_list:

if os.path.isfile(dir_item) == False:

  rez_count = rez_count + dir_checker(root_path + dir_item + "/", keyword)

if os.path.isfile(dir_item) == True and dir_item.__contains__(keyword):

  rez_count += 1

return rez_count

print(find(dir, “.py”))

I could not figure this out without using nested functions, maybe there is a possibility to do all of this in one function…

Please put the entire file within 1 pair of triple backticks and with proper indentation (at least 2 spaces per indent) and without a blank line between every line.

You gave two separate problems to solve: find a file whose name matches a pattern, and count files whose names follow a pattern.

os.walk and os.scandir do the directory recursion needed, but I presume you are supposed to duplicate their functionality.