[Bug | Cursor] import error: No module named ‘data‘

import error: No module named 'data'

Folder Structure

Failed Script

python 复制代码
ROOT_DIR = Path(__file__).parent.parent
os.chdir(ROOT_DIR)
print(f"Using root directory: {ROOT_DIR}")

from data.dataloader import seq_collate

It is right to set the ROOT_DIR and calling os.chdir(ROOT_DIR), but changing the working directory via os.chdir() does not affect Python's module resolution (sys.path).

🔍 Why your current approach failed

  • os.chdir(ROOT_DIR) affects where relative files are opened (open(), etc.)
  • But from data... uses sys.path (which defaults to the directory the script is launched from)
  • So data wasn't found in any of the directories listed in sys.path

✅ Final Fix: Explicitly Add ROOT_DIR to sys.path

python 复制代码
# Define the root dir of your project
ROOT_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT_DIR))  # ← THIS IS THE FIX
print(f"Using root directory: {ROOT_DIR}")

from data.dataloader import seq_collate