开发者

importing files in python

I have that file structure-

  1. Blog\DataObjects\User.py

  2. Blog\index.py

I want to import the function(say_hello) at User.py from index.py. I am trying this code -

from Blog.DataObjects.User import say_hello

say_hello()  

And I have that error -

Traceback (most recent call last):
  File "index.py", line 1, in <module>
    from Blog.DataObjects import User
ImportError: No module named Blog.D开发者_JS百科ataObjects


Python expects in every directory that should be importable, a file __init__.py, which may be empty. So, if you correct your file structure to this:

Blog/__init__.py
Blog/index.py
Blog/DataObjects/User.py
Blog/DataObjects/__init__.py

it should work, if the path to the directory is in your Python path (you can check this with:

import sys
print sys.path

). If not, mind that importing is done relative to the position of the current file. That is, since index.py is already inside Blog, the import should read:

from DataObjects.User import say_hello


from DataObjects.User import say_hello
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜