It occurs to me that it might be useful if Python provided a function to search for a file with a given name in various directories (much as the import.import_lib function searches for a module in the directories in sys.path).
This function would perhaps be best placed in the os.path or os modules.
To start the ball rolling, I offer this version:

import sys
import os

def findfile(fileName, *PathLists):
    if not PathLists:
        # Default to searching just sys.path:
        PathLists = [ sys.path ]
        # This may or may not be the most useful default;
        # there is a case for having no default, forcing calls of this function
        # to explicitly specifiy which paths they want to search,
        # and perhaps raise an Exception if they don't;
        # suggestions welcome.

    for pList in PathLists:
        # if pList is a str, assume it is a semicolon-separated list of directories
        # (like the PATH and PYTHONPATH environment variables);
        # otherwise assume it is a sequence of paths (like sys.path):
        if isinstance(pList, str):
            pList = pList.split(';')

        for path in pList:
            filePath = os.path.join(path, fileName)
            if os.path.isfile(filePath):
                return filePath
                # Return first match found.
                # Another possibility is to return a list of all matches.
    return None

Then e.g.
    print(findfile('os.py'))
would print something like
    C:\Python311\Lib\os.py

This idea was partly inspired by Michael Stemper asking about best practice for placing, and finding, a configuration file.
Thoughts?

Best wishes
Rob Cliffe
--
https://mail.python.org/mailman3//lists/python-list.python.org

Reply via email to