繁体   English   中英

导入软件包时找不到模块

[英]Module not found when importing package

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

(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导入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

您需要在主文件中再打一个电话。 当前,您已经从funktio导入了文件tulosta ,但是,您需要访问该文件中的function / 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM