1

I have a Python directory like this, and I am trying to import classes from main_script.py.

 - main_folder
   - main_script.py
 - resources
   - package_folder
     - class_files
       - class1.py
       - class2.py
       - class3.py
       - __init__.py

This is what I tried

sys.path.append('../resources/package_folder)
from class_files import *

But I get this error, "No module named 'class_files'"

3
  • 1
    You are using a relative path, and it will be relative to your process's current working directory, not necessarily where the main_script.py is located. Commented Aug 5, 2020 at 13:01
  • So how would I find that? I did print sys.path but I got a bunch of things, hard to pinpoint what the working directory is. Commented Aug 5, 2020 at 13:04
  • Edit: Yeah so I did print(os.getcwd()) and it says the working directory is where main_script.py is Commented Aug 5, 2020 at 13:10

1 Answer 1

1

You have a relative path in your sys.path which is relative to the process's current directory rather than the location of the main_script.py script itself.

You can use instead:

import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__),
                             '../resources/package_folder'))

from class_files import *

or if you prefer:

sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)),
                             'resources/package_folder'))

Separately, you might also find that in your __init__.py you need:

__all__ = ['class1', 'class2', 'class3']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.