Import module from file path

Oscar Benjamin oscar.j.benjamin at
Wed Dec 5 06:42:03 EST 2018

On Wed, 5 Dec 2018 at 07:57, Peter Otten <__peter__ at> wrote:
> Oscar Benjamin wrote:
> >
> > I'm looking to import a module given a string representing the path to
> > the .py file defining the module.
> I am not aware of a clean way. I have used
> def guess_modulename(filename):
>     """Infer module name from filename.
>     >>> guess_modulename("/foo/bar/")
>     'baz'
>     >>> guess_modulename("/usr/lib/python3.4/logging/")
>     'logging.handlers'
>     """
>     if not filename.endswith(".py"):
>         raise ValueError("expecting .py file, but got %r" % filename)
>     filename = filename[:-3]
>     folder, name = os.path.split(filename)
>     names = [name]
>     while os.path.isfile(os.path.join(folder, "")):
>         folder, name = os.path.split(folder)
>         names.append(name)
>     return ".".join(reversed(names))
> which unfortunately does not work with namespace packages.

Thanks Peter. I don't need to worry about namespace packages thankfully.

Thinking about this some more I can see that although the mapping from
module names to file paths needs to be well defined for normal imports
to work the reverse mapping will not always be well defined. For one
there are namespace packages. For another there maybe multiple routes
from sys.path to a particular .py file so that it might be possible to
import a.b.c.stuff as c.stuff if a/b is also in sys.path. Maybe that's
why a ready made solution doesn't seem to exist: the problem itself
isn't well-posed.


More information about the Python-list mailing list