ImportError: no module named utils

I am trying to import a utility file, but starting in a weird error only when I run the code through a script.

When running test.py

location: /home/amourav/Python/proj/test.py

the code:

import os os.chdir(r'/home/amourav/Python/') print os.listdir(os.getcwd()) print os.getcwd() from UTILS import * 

Output:

['UTILS_local.py', 'UTILS.py', 'proj', 'UTILS.pyc']

/ home / amourav / Python

Traceback (last last call): File "UNET_2D_AUG17.py", line 11, from from import UTILS * ImportError: There is no module named UTILS

but when I run the code through the bash terminal, it works fine

 bash-4.1$ python >>> import os >>> os.chdir(r'/home/amourav/Python/') >>> print os.listdir(os.getcwd()) 

['UTILS_local.py', 'UTILS.py', 'proj', 'UTILS.pyc']

 >>> from UTILS import * 

blah blah - all right - blah blah

I am running Python 2.7.10 on a Linux machine

+7
python import module python-module
source share
1 answer

Your project is as follows:

 +- proj | +- test.py +- UTILS.py +- ... 

If you want to import UTILS.py, you can choose:

(1) add the path to sys.path in test.py

 import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), "..")) # now you may get a problem with what I wrote below. import UTILS 

(2) create package (import only)

 Python +- proj | +- test.py | +- __init__.py +- UTILS.py +- __init__.py +- ... 

Now you can write this in test.py if you import Python.proj.test :

 from .. import UTILS 

INCORRECT ANSWER

I have had this error several times. I think I remember.

Fix: do not run test.py , run ./test.py .

If you look at sys.path , you will see that there is an empty line inside which is the path to the file.

  • test.py adds '' to sys.path
  • ./test.py adds '.' in sys.path

Import can only be done from "." , I think.

+4
source share

All Articles