导入包时找不到模块



即使在谷歌搜索,尝试了一百万件事等之后,我也无法让包导入正常工作。我有一个简单的文件夹结构,如下所示:

(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:KouluhommelitScript-programmingmoduuliharkkamain.py", line 4, in <module>
tulosta.tulosta()
NameError: name 'tulosta' is not defined

如果我尝试将"从图洛斯塔导入图洛斯塔"放入初始化文件中,我会得到

Traceback (most recent call last):
File "E:KouluhommelitScript-programmingmoduuliharkkamain.py", line 1, in <module>
import funktio.tulosta
File "E:KouluhommelitScript-programmingmoduuliharkkafunktio__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], ':nt','Head honcho:', country_data.countries[country_data.codemap[code]]['head honcho'],'nt','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

您需要在主文件中进行一次额外的调用。目前,您已从funktio导入文件tulosta,但是,您需要访问该文件中的函数/类/变量。tulosta.tulosta()不包括文件夹名称,这仍然是必需的 主要:

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

如果确实要以tulosta.tulosta()身份调用tulosta(),请使用别名导入:

import funktio.tulosta as tulosta
tulosta.tulosta()

最新更新