Jupyter Notebook无法导入其他文件夹Python函数问题求助(Anaconda环境)
Hey there, I’ve dealt with this exact headache plenty of times while working with Jupyter and Anaconda—let’s break down the most reliable fixes to get your imports working:
1. Add the Target Folder to Python’s Path Directly
Python can only find modules in directories listed in its system path. You can manually add your target folder right in your Jupyter notebook:
import sys # Replace this with the absolute path to your folder containing the Python functions sys.path.append("/full/path/to/your/target/folder") # Now you can import your module import your_module_name # Make sure this matches the .py file name (without .py)
If you prefer relative paths (to avoid hardcoding absolute paths), use the os module to dynamically build the path:
import sys import os # Get the directory where your current Jupyter notebook is saved current_notebook_dir = os.getcwd() # Example: if your target folder is one level up from the notebook target_folder = os.path.join(current_notebook_dir, "../your_target_folder") sys.path.append(target_folder)
2. Turn the Target Folder into a Python Package
Python treats folders with an __init__.py file as importable packages. Just create an empty file named __init__.py in the folder holding your functions—you don’t even need to put anything inside it. This tells Python to recognize the folder as a valid module source.
3. Verify You’re Using the Correct Anaconda Environment
Sometimes Jupyter is using a different Anaconda environment than the one where your setup lives. To check:
Run this in your notebook:
import sys print(sys.executable)
Compare the output path to your active Anaconda environment’s Python executable. If they don’t match, add your environment as a Jupyter kernel:
- Open your terminal/command prompt and activate your environment:
conda activate your_environment_name - Install the ipykernel package:
conda install ipykernel - Register the environment as a Jupyter kernel:
python -m ipykernel install --user --name your_environment_name --display-name "Python (your_environment_name)" - Restart Jupyter Notebook and select the newly added kernel from the "Kernel > Change Kernel" menu.
4. Double-Check Module Names and File Case
- Make sure the module name you’re importing matches the
.pyfile exactly (e.g., if your file isdata_utils.py, importdata_utils, notDataUtils). - On Linux/macOS, filenames are case-sensitive—so
Utils.pyis different fromutils.py.
Start with the first two fixes—they usually resolve the issue quickly. If not, move on to checking your environment and file naming.
内容的提问来源于stack exchange,提问作者erez

