Python导入错误:没有名为'convert.py'的模块

2 投票
2 回答
7595 浏览
提问于 2025-04-18 09:20

我在这个网站上找了找类似的问题,但似乎没有人遇到和我一样的困扰。

为了写一本关于Python的教程书,我写了一个程序,用来把摄氏温度转换成华氏温度。当我在IDLE这个环境里运行它的时候,程序是能正常工作的,但却返回了一个错误。以下是我写的程序代码:

#convert.py
#converts Celsius temperatures to Farenheit

        def main():
            celsius = input("Type the temperature in degrees Celsius: ")
            farenheit = ((9/5)* int(celsius)) +  32
            print(farenheit)

    main();

这是我遇到的错误信息。

>>> import convert.py
Type the temperature in degrees Celsius: 59
138.2
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    import convert.py
ImportError: No module named 'convert.py'; 'convert' is not a package

我使用的是Python 3.4.1版本。

2 个回答

1

你需要去掉 .py 这个后缀;在Python中导入模块时只用基本的名字:

import convert

发生的事情是,Python导入了 convert,然后它会去找一个叫 py 的嵌套模块。这个步骤失败了,因为 convert 不是一个包,不能包含其他模块。

6

在导入Python模块时,不需要加文件扩展名。你应该这样做:

>>> import convert

这段代码:

>>> import convert.py

是在告诉Python去导入一个不存在的py模块,这个模块位于convert这个包里。

这里有一个关于在Python中导入模块和包的参考资料

撰写回答