Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #60349

Re: Importing by file name

References <CAPTjJmqhiyT9zVHFRyKH0UwhdhFgZxA1rcbarChePMyfK7dDTA@mail.gmail.com>
From Devin Jeanpierre <jeanpierreda@gmail.com>
Date 2013-11-23 20:06 -0800
Subject Re: Importing by file name
Newsgroups comp.lang.python
Message-ID <mailman.3115.1385266044.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Nov 23, 2013 at 7:41 PM, Chris Angelico <rosuav@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Importing by file name Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-11-23 20:06 -0800

csiph-web