Importing by file name

Devin Jeanpierre jeanpierreda at gmail.com
Sat Nov 23 23:06:42 EST 2013


On Sat, Nov 23, 2013 at 7:41 PM, Chris Angelico <rosuav at gmail.com> wrote:
> As part of a post on python-ideas, I wanted to knock together a quick
> little script that "imports" a file based on its name, in the same way
> that the Python interpreter will happily take an absolute pathname for
> the main script. I'm sure there's a way to do it, but I don't know
> how. Obviously the import statement can't do it, but I've been poking
> around with __import__ and importlib without success. (Experiments are
> being done on Python 3.3; if a different version would make the job
> easier I'm happy to switch. This is just a curiosity tinkering.)

The easiest way is probably to modify what directories python searches
- sys.path:

import os
import sys

def file_import(path):
    dname, fname = os.path.split(path)
    modname, _ext = os.path.splitext(fname)
    sys.path.insert(0, dname)
    try:
        return __import__(modname)
    finally:
        del sys.path[0]

-- Devin



More information about the Python-list mailing list