Selected file importation problem !

David Bolen db3l at fitlinxx.com
Wed May 23 15:08:40 EDT 2001


vitiere at lure.u-psud.fr (Erwan) writes:

> I used wxpython 2.2 with python 1.5.2.
> In my open file dialog , I get a string which contains a file name (.py 
> extension).
> I want to import the module named like the file name I get, but I don't 
> know how to do this operation.

The easiest way to perform an import based on a string name of the
module is __import__ (a built-in function - see the library reference,
section 2.3).  You'll need to strip off the .py extension since import
just wants the module name, and as it behaves identically to "import"
you need to ensure that the selected file is part of the import search
path (sys.path).  But you can always manually add a selected directory
to sys.path before doing the import.

It doesn't automatically rebind any local namespace references but it
returns a module object, so:

	import xxxx

can be reproduced by:

	xxxx = __import__("xxxx")

There are other options depending on what you are trying to do with
the module - for example, you could directly execfile() the file into
its own dictionary to use to access the module, but that wouldn't
quite be the same as an import.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list