My python somehow can't find any modules in the same directory. What am I doing wrong? (python2.7)
So I have one directory '2014_07_13_test', with two files in it:
where hello.py:
# !/usr/local/bin/python # -*- coding: utf-8 -*- def hello1(): print 'HelloWorld!'
and test.py:
# !/usr/local/bin/python # -*- coding: utf-8 -*- from hello import hello1 hello1()
Still python gives me
>>> Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 4, in <module> ImportError: No module named hello
What's wrong?
This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.
Typically, that means Python and all packages will get installed to a directory under /usr/local/bin/ for a Unix-based system, or \Program Files\ for Windows. Conversely, when a package is installed locally, it's only made available to the user that installed it.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Change your import in test.py to:
from .hello import hello1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With