当我尝试导入当前工作目录中的模块时出现 ModuleNotFoundError

ModuleNotFoundError is raised when I try to import a module that is in my current working directory

我在网络驱动器上安装了 Python。我使用 pushd 命令进入同一网络驱动器上我的项目文件夹。我在该文件夹中打开 python。我尝试导入该文件夹中的模块。提出了一个ModuleNotFoundError

C:\users\myprofile>pushd \network\drive\my\directory\my-program
U:\my\directory\my-program>"\network\drive\Python\installations\python-3.8.3rc1-embed-win32\python.exe"
Python 3.8.3rc1 (tags/v3.8.3rc1:802eb67, Apr 29 2020, 21:21:45) [MSC v.1925 32 bit (Intel)] on win32
>>> import os
>>> import dict2obj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'dict2obj'
>>> os.listdir()
['config.yml', 'dict2obj.py', 'files', 'main.py', 'start.bat', 'templates', '__pycache__']

我使用 os.listdir() 查看当前工作目录中有哪些文件。

我不明白这个问题与在网络驱动器上有什么关系。

更新:即使我执行了以下操作,问题仍然存在:

import os
os.chdir("\\network\drive\my\directory\my-program")

编辑:请不要将此标记为 Python can't find module in the same folder 的副本。它不是。在那篇文章中,OP 没有确认他们的工作目录是正确的,不像这个问题。

编辑:这是 sys.path 中的所有内容:

\network\drive\Python\installations\python-3.8.3rc1-embed-win32\python38.zip
\network\drive\Python\modules\site-packages
\network\drive\Python\modules\custom-modules
\network\drive\Python\installations\python-3.8.3rc1-embed-win32
>>> os.listdir()
# can't see __init__.py file here!
['config.yml', 'dict2obj.py', 'files', 'main.py', 'start.bat', 'templates', '__pycache__']
  • 模块文件夹需要 __init__.py 个文件才能导入。

检查#https://docs.python.org/3/reference/import.html#regular-packages

我的解决方案是删除此文件:

python39._pth

这允许 Pip 工作,也允许来自同一目录的 import。 或者你可以得到这个:

https://nuget.org/packages/python

点击“下载包”,即可像Zip文件一样解压

如前所述,您的文件夹既没有 __init__.py 表示它是一个模块,也没有 __main__.py 表示起点,您也没有指定 from . import dict2obj

另请分享您的 sys.path 以便我们查看是否正在考虑当前文件夹。