You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

sys.path.append未生效,如何自动导入同目录下的Python模块?

Fixing Your Module Import Issue

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

  1. Incorrect Path Added to sys.path
    You're adding the arrayUtilities directory itself to sys.path, but Python needs the parent directory of arrayUtilities (which is your script's directory) in sys.path to recognize arrayUtilities as an importable module. Adding the module directory directly makes Python look inside it for modules, not treat the directory as a module itself.

  2. os.getcwd() Might Not Point to Your Script's Directory
    os.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 locate arrayUtilities.

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__.py File to arrayUtilities
    While Python 3.3+ supports namespace packages without this file, creating an empty __init__.py inside the arrayUtilities directory 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:32:32