Python3。ImportError:没有名为“ myfile”的模块

Mar*_*ark 5 python unix macos

iMac-Mark:~ Mark$ python3
Python 3.3.2 (v3.3.2:d047928ae3f6, May 13 2013, 13:52:24) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import myfile
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'myfile'
Run Code Online (Sandbox Code Playgroud)

我是Python和一般编程的新手。我读了一些有关的文章sys.path__PATH__但我什么都不懂。

itd*_*xer 5

解决方案:

  1. __init__.py在附近存档myfile.py吗?
  2. 你有你的目录sys.path吗?(如果没有像这样添加它 sys.path.append('path/to/python/code'))
  3. 如果您尝试从 python 环境导入它,则需要在此文件附近运行 python shell

您也可以尝试运行此代码

import sys
print(sys.path)
Run Code Online (Sandbox Code Playgroud)

在您的输出中,您可以看到 python 看到的所有目录的列表。如果您的文件在任何其他目录中,则必须更改目录或 pythonsys.path

你可以这样做

$ python3
>>> import sys
>>> sys.path.append('/all/path/to/Desktop/Python')
>>> import myfile
Run Code Online (Sandbox Code Playgroud)

或者像这样

$ cd ~/Desktop/Python
$ python3
>>> import myfile
Run Code Online (Sandbox Code Playgroud)