Jupyter笔记本无法从其他文件夹导入python函数

2024-06-16 09:39:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Jupyter笔记本,我想使用本地python函数从我的计算机中的其他文件夹。 当我导入这些函数时,会出现以下错误: “ModuleNotFoundError:没有名为'xxxxxxxxxxxx'的模块

  • 我用水蟒做python解释器

Tags: 模块函数文件夹计算机错误笔记本jupyter解释器
3条回答

听着,在Python2.7上是可行的,但是在Python3上会出现一些错误。。。

如果在其他文件中编写某些函数,则需要导入此文件。如果这个文件在同一个文件夹中-它是好的。但如果在子文件夹中。。。在子文件夹中,需要创建空文件init 现在,如果你尝试从子文件导入你的模块-也可以

阳痿(对于python 3)
使用此代码

&13;
&13;
import os
import sys

sys.path.append(os.getcwd() + '/modules')
import my_module

如果还没有,请尝试在代码中使用函数的完整路径名。

from Folder1.Folder2.FileName import ModuleName

someVar = ModuleName(params)

Folder1将是主程序所在目录中的文件夹。 另外,在您从中导入的每个文件夹中创建一个名为__init__.py的空文件。

可以使用sys将路径添加到本地模块/python文件中。

import sys
sys.path.append("/path/to/file/")  # path contains python_file.py

import python_file

如果您想通过向Anaconda路径添加模块获得更持久的解决方案,请参阅cord kaldemeyerhttps://stackoverflow.com/a/37008663/7019148中的上一个答案。为完整起见,复制以下内容:

I found two answers to my question in the Anaconda forum:

1.) Put the modules into into site-packages, i.e. the directory $HOME/path/to/anaconda/lib/pythonX.X/site-packages which is always on sys.path. This should also work by creating a symbolic link.

2.) Add a .pth file to the directory $HOME/path/to/anaconda/lib/pythonX.X/site-packages. This can be named anything (it just must end with .pth). A .pth file is just a newline-separated listing of the full path-names of directories that will be added to your path on Python startup.

Both work straightforward and I went for the second option as it is more flexible.

*** UPDATE:

3.) Create a setup.py in the folder of your package and install it using pip install -e /path/to/package which is the cleanest option from my point of view because you can also see all installations using pip list.

Thanks anyway!

相关问题 更多 >