Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing user defined modules in python from a directory

I'm trying to import a module I wrote in python that just prints out a list containing numbers. The issue I'm having is that I want to be able to import it from a separate directory but the answers I have read so far don't seem to be working for my situation.

For example, given I want to import printnumbers.py from a directory in my documents folder I am supposed to implement the following:

    import sys
    sys.path.append('/home/jake/Documents')
    import printnumbers.py

This snipit of code results in a "Import error" telling me that the specified module does not exist. I'm not exactly sure where to proceed from here, I have checked multiple times to make sure it's the right spelling for the path as well as for the module name. I'm still trying to understand exactly what appending to the "sys.path" does. From what I understand it's telling the program to search for modules in that directory?

Thanks for anyone who answers my rather novice question. I'm just looking for a better understanding of it that the python documentation isn't providing for my frame of mind.

like image 961
Ragecoder Avatar asked May 30 '16 01:05

Ragecoder


2 Answers

When the file is printnumbers.py, the module is called printnumbers (without the .py). Therefore use

import printnumbers

import sys
sys.path.append('/home/jake/Documents')

appends '/home/jake/Documents' to the end of sys.path. The directories listed in sys.path are searched (in the order listed) whenever an import statement causes Python to search for a module. (Already imported modules are cached in sys.modules, so Python does not always need to search sys.path directories to import a module...)

So if you have a file /home/jake/Documents/printnumbers.py, then import printnumbers will cause Python to import it provided there is no other file named printnumbers.py in a directory listed in sys.path ahead of /home/jake/Documents/.

Note that injecting directories into sys.path is not the usual way to set up Python to search for modules. Usually it is preferable to add /home/jake/Documents to your PYTHONPATH environment variable. sys.path will automatically include the directories listed in the PYTHONPATH environment variable.

like image 166
unutbu Avatar answered Sep 27 '22 22:09

unutbu


and one more thing, use an empty __ init __.py file in you directory to make it as a python package (only then Python will know that this directory is a Python package directory other than an ordinary directory). Thus you can import modules from that package from different directory.

like image 21
Amitkumar Karnik Avatar answered Sep 27 '22 23:09

Amitkumar Karnik