Reputation: 23
I'm running Python3.6 on Mac OSX 10.12.4
/Documents/PyProjects/modules/
In that directory, resides __init__.py
and Pyrime.py. Pyrime.py has some functions in it.
/Documents/PyProjects/PE010/
In that directory resides my program: PE010_Summation_of_Primes.py
. I want to import one function, called is_prime
, in Pyrime.py
to use in PE010_Summation_of_Primes.py
. I thought all I would need to do is write, in PE010_Summation_of_Primes.py
:
from modules.Pyrime import is_prime
This doesn't work. My terminal throws:
Traceback (most recent call last):
File "PE010_Summation_of_Primes.py", line 1, in <module>
from Pyrime import is_prime
ModuleNotFoundError: No module named 'Pyrime'
Python is the first language I've ever seen, and I've only seen it for about a week so far. I've looked at a lot of documentation, but for a beginner like me, it hasn't been very enlightening.
Upvotes: 2
Views: 454
Reputation: 6962
Well, python refers the global library directory or local directory when trying to import a file. But for files in directories other than local you can either add file path to sys.path
or create a __init__.py
file in all directories including the parent directory PyProjects
. Try this -
from modules.Pyrime import is_prime
So your directory will look something like this -
PyProjects
-- __init__.py
-- PE010
-- __init__.py
-- PE010_Summation_of_Primes.py
-- modules
-- __init__.py
-- Pyrime.py
Hope it helps.
Upvotes: 1
Reputation: 170
Add the system-path at runtime:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
it will work!
Upvotes: 0