Find file in nested folder and dynamically import the file as a module in python

114 Views Asked by At

Lets say I have a file structure as follows:

folder1
  --file1.py

  folderStart
    --start.py

  folder2
    --file2.py

  folderX
    --fileX.py
  ...

In start.py, I get a name of a file dynamically, for example: file_name = "file3"

I dont know where the "file3" is, as I dont get the file path with it. It could be anywhere in folder1 or a subfolder: folder2, folderX etc. I then need to dynamically import the "file3" and for that I need to know its relative path to start.py.

import_module(f"{file_path}")

How do I find the "file3" and its path so I can call the import?

Thanks for any replies, I am a beginner so sorry if unclear. Tried getting the relative path unsuccessfully

**Edit: All files and folders have random names, unsorted Also, theres a file structure above folder1 and I only need to look inside folder1.

1

There are 1 best solutions below

2
Unnikrishnan Namboothiri On

This should help you

import os
def find_file(root_folder, target_file):
    for root, dirs, files in os.walk(root_folder):
        if target_file in files:
            return os.path.join(root, target_file)
    return None

root_folder = '/path/to/unknown/root/folder'
target_file = 'file_name.txt'

file_path = find_file(root_folder, target_file)

if file_path:
    print(f"File '{target_file}' found at: {file_path}")
else:
    print(f"File '{target_file}' not found in the specified folder.")```