sys.path.append未生效,如何自动导入同目录下的Python模块?
Let's break down why your current code isn't working and walk through the fixes step by step:
Core Problems with Your Existing Code
Incorrect Path Added to
sys.path
You're adding thearrayUtilitiesdirectory itself tosys.path, but Python needs the parent directory ofarrayUtilities(which is your script's directory) insys.pathto recognizearrayUtilitiesas an importable module. Adding the module directory directly makes Python look inside it for modules, not treat the directory as a module itself.os.getcwd()Might Not Point to Your Script's Directoryos.getcwd()returns the folder you're running the script from, not the folder where the script is stored. If you execute the script from a different directory, this will lead to a wrong path, so your code won't locatearrayUtilities.
Corrected Code
Here's the fixed version that addresses both issues:
import sys import os # Get the absolute path of the directory containing your script script_directory = os.path.dirname(os.path.abspath(__file__)) # Add the script's directory to sys.path (in case it's not already included) if script_directory not in sys.path: sys.path.append(script_directory) # Now you can import the module correctly import arrayUtilities as arr
Extra Checks to Guarantee Success
Add an
__init__.pyFile toarrayUtilities
While Python 3.3+ supports namespace packages without this file, creating an empty__init__.pyinside thearrayUtilitiesdirectory explicitly tells Python it's an importable module, avoiding any edge cases.Debug with Path Prints
If you want to verify everything is set up right, add these lines to check the paths:print("Script directory:", script_directory) print("sys.path contents:", sys.path)
This should resolve the import issue by ensuring Python looks in the correct location for your arrayUtilities module.
内容的提问来源于stack exchange,提问作者Saverio

