[Pythonmac-SIG] importing from nested folders?
Jack Jansen
jack@oratrix.nl
Fri, 07 Apr 2000 12:36:02 +0200
> Newbie Q:
>
> I am trying to understand the use of paths and folders and import and/or reload.
> I have a folder on my Mac whose path is in the sys.path. I have a folder in this folder (with spaces in the name...a problem?) and I want to import a file with its functions from that nested folder.
There are three answers to this:
The quick answer is "you can't".
The pedantic answer is that you shouldn't want to do this. You're thinking of
"import" as a mechanism to load files into Python, but the philosophy is
exactly the reverse: import imports modules, and the filesystem happens to be
a handy place to store modules, but that means that the part of the filesystem
used to store modules has to adhere to the Python conventions: the folder
should be in sys.path, the filename should end in ".py", the rest of the
filename should be an identifier (start with a letter and then letters, digits
and _) and there shouldn't be upper/lowercase conflicts.
The useful answer is that there are many ways to extend sys.path without
reverting to EditPythonPrefs. The most useful one is that the folder
containing the main script is automatically added to sys.path. So, if you have
a "main.py" in a folder with "sub1.py" and "sub2.py" you can double-click
main.py, and "import sub1" will work. You can also manually do
import sys
sys.path.append("Macintosh HD:My Documents:Handy Python Modules")
at the beginning of your script. And you may want to look up packages in the
Python manual, these don't quite do what you ask (a package is a folder full
of modules, and it is itself a module too from a Python point of view) but it
may be near enough.
--
Jack Jansen | ++++ stop the execution of Mumia Abu-Jamal ++++
Jack.Jansen@oratrix.com | ++++ if you agree copy these lines to your sig ++++
www.oratrix.nl/~jack | see http://www.xs4all.nl/~tank/spg-l/sigaction.htm