导入包时找不到模块

时间:2018-01-12 00:16:23

标签: python import

即使经过谷歌搜索,尝试了一百万件事,我也无法让包导入正常工作。我有一个像这样的简单文件夹结构:

(main folder)
                     ---------------
funktio (folder)---->| __init__.py |
main.py              | tulosta.py  |
country_data.py      ---------------

基本上我正在尝试将tulosta.py导入main.py. Tulosta.py有一个函数可以打印来自country_data.py的某些东西。到目前为止,当我将tulosta.py的内容粘贴到main.py并从main.py中删除tulosta.py的导入时,该程序正常工作(因此脚本正确地从country_data读取)。我正在做一个学校作业,它需要导入一个模块和一个包。我的问题是,如果我试着

import funktio.tulosta

我只得到

Traceback (most recent call last):
  File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 4, in <module>
tulosta.tulosta()
NameError: name 'tulosta' is not defined

如果我尝试将“从tulosta import tulosta”放入init文件中,我会

Traceback (most recent call last):
File "E:\Kouluhommelit\Script-programming\moduuliharkka\main.py", line 1, in <module>
import funktio.tulosta
File "E:\Kouluhommelit\Script-programming\moduuliharkka\funktio\__init__.py", line 1, in <module>
from tulosta import tulosta
ModuleNotFoundError: No module named 'tulosta'

所以基本上无论我尝试什么,我都会收到错误代码。这是main.py中的代码:

import funktio.tulosta
import country_data

tulosta.tulosta()

和tulosta.py:

def tulosta():
    for code in country_data.countrycodes:
            print (country_data.codemap[code], ':\n\t','Head honcho:', country_data.countries[country_data.codemap[code]]['head honcho'],'\n\t','Population:', country_data.countries[country_data.codemap[code]]['population'],'million')

在经历了4个多小时的努力之后,我真的变得绝望了。这似乎是一个简单的操作,但显然不是。请帮忙。如果需要,我会提供更多信息。

这是作业:

Rearrange the code from previous exercises:

Make a folder called "moduuliharkka"
Make a python file called "country_data" where you put the lists and dicts from the exercise 15.
Then make a new folder inside the moduuliharkka-folder called "funktio" (tip: init)
Put the code from exercise 16. inside a function and save it as a .py file in the funktio-folder
Go back to your moduuliharkka-folder, make a main.py file where you import the country_data module and the funktio folder as a package
Call the function imported in the main.py script

1 个答案:

答案 0 :(得分:0)

您需要在主文件中再拨一个电话。目前,您已从tulosta导入文件funktio,但是,您需要访问该文件中的函数/ class / variable。 tulosta.tulosta()不包括仍需要的文件夹名称 主要:

import funktio.tulosta
functio.tulosta.tulosta() #call the function in "tulosta" here

如果您确实要将tulosta()称为tulosta.tulosta(),请使用别名导入:

import funktio.tulosta as tulosta
tulosta.tulosta()
相关问题