0

I have a python project a folder structure like this:

main_directory
  main.py
  drivers
    __init__.py
    xyz.py
  utils
    __init__.py
    connect.py

I want to import connect.py into xyz.py and here's my code:

from utils import connect as dc

But I keep getting this error no matter what I do, please help:

ModuleNotFoundError: No module named 'utils'

Update: People are telling me to set the path or directory, I don't understand why I need to do this only for importing file. This is something that should work automatically.

Amol Borkar
  • 2,321
  • 7
  • 32
  • 63
  • Why did you tag `pip`? Is it relevant to your question? You do not mention pip in the question. -- How do you run your code? Which command? And from which working directory? – sinoroc Jan 20 '23 at 12:25

4 Answers4

0

In your utils folder __init__.py should be blank. If this doesn't work, try adding from __future__ import absolute_import in your xyz.py file.

BVB44
  • 266
  • 2
  • 11
-1

You could move your utils folder into drivers, making the path to the to-be imported file a subdirectory of your executing file, like:

main_directory/drivers/utils/connect.py

Alternatively, you could try

from ..utils import connect as dc

This will move up a directory before import.

Lasty, you could add the directory to Path in your script via

import sys
sys.path.insert(0,'/path/to/mod_directory')

For this method, see also this question

Jonas
  • 1
  • 2
-1

Check your current directory. It must be main_directory.

import os
print("Current working directory is: ", os.getcwd()

if not, you can change using

os.chdir("path/to/main_directory")

also works with relative path

os.chdir('..')
-1

I was also facing same problem when you use row python script so i use the following code at the beginning of the file

import os
import sys

current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)

This way it will search the require file at parent directory.

Hope this will work for you also..

DecoderS
  • 64
  • 6