0

I have a main.py file in the folder project and read.py in the folder ./project/utils. In the main.py, I called

import sys, os
sys.path.append('./utils/')
from utils.read import function1

However, when I use the python main.py command, I got the error ImportError: No module named utils.read. What should I change? Thanks all

John
  • 2,838
  • 7
  • 36
  • 65

2 Answers2

4

i think you need to add __init__.py

in your directory..

make sure you have __init__.py in utils folder.. then only python will understand it is package folder contains py

Mohideen bin Mohammed
  • 18,813
  • 10
  • 112
  • 118
1

__init__.py specifies that the folder is actually a package. a package in python is a directory containing .py files (modules). In every folder which is a package (that is, a folder containing multiple .py files) you should define __init__.py. It can be empty, or you can put some statements to execute when the package is imported (or modules from the package).

For exmaple, let's take this directory tree: /dev/package/greeter.py and current working directory is /dev.

>>> from package import greeter

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    from package import greeter
ImportError: No module named package

import pakcage results in the same error. When adding __init__.py into the package folder, it works. My init is simple as

print 'init executed'

>>> from package import greeter
init executed

>>>

One common functionality to put in __init__.py is the __all__ variable. You can read more about it here Can someone explain __all__ in Python?

Chen A.
  • 10,140
  • 3
  • 42
  • 61