Reputation: 3356
I have an exercise for a course in Python I have to complete. I have saved my methods/defs in one file and just need to figure out how to run it. I was hoping you could explain to me how to import files (I know the syntax"import filename"). When ever I do this I get an error. How do I change the file path of the import to the file on my desktop? I am using a mac and running IDLE 2.7.3
Upvotes: 0
Views: 13808
Reputation: 85095
On Mac OS X, there are two basic ways to launch IDLE. One is by double-clicking on an IDLE icon from the Applications folder in the Finder. (I'll call that IDLE.app
) The second is to launch IDLE from a terminal session shell with something like:
idle2.7
I'll call that bin/idle
because it refers to file in one of your system's bin
directories.
When launching bin/idle
, IDLE will inherit the current working directory of the shell and will add that directory to the front of the list of directories Python searches for imports. You can examine that list of directories in the IDLE shell window:
import sys
sys.path
When you launch IDLE.app
, however, it is not associated with any shell so there is no opportunity to tell IDLE which working directory to use. In this case, IDLE.app
uses your Documents
folder/directory as its working directory: in shell notation, ~/Documents
, also spelled /Users/your_login_name/Documents
.
You can manually manipulate sys.path
in your Python program to add another directory for imports:
import sys
sys.path.insert(0, '/path/to/directory')
Another way to manipulate sys.path
is to use the PYTHONPATH
environment variable. But, again, when using IDLE.app
, there is no (easy) way to pass environment variables to it, unlike with bin/idle
So if you want to use IDLE.app
, the simplest approach is to put into your Documents
directory all of the files and packages directories that you want to be able to import. Otherwise, use a terminal session, set the desired working directory and/or PYTHONPATH
variable and launch bin/idle
. So something like:
cd ~/MyProject
export PYTHONPATH=~/"AnotherPackageDirectory"
idle2.7
Yet another approach is to install your modules in the default locations that Python searches and use Distutils or easy_install
or pip
. But that's something to learn about later when you have a finished project.
Upvotes: 0
Reputation: 3133
If the files are in the same directory as that file you can just use
import <filename> #(without the <>)
However, if you are referring to the files in a separate directory use imp
import imp
module = imp.load_source('module.name', '/path/to/file.py')
module.SomeClass()
Upvotes: 1