Can't Get Python to Import from a Different Folder

Can't get Python to import from a different folder

I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.

Then you can do:

from Models.user import User

You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.

Importing modules from parent folder

It seems that the problem is not related to the module being in a parent directory or anything like that.

You need to add the directory that contains ptdraft to PYTHONPATH

You said that import nib worked with you, that probably means that you added ptdraft itself (not its parent) to PYTHONPATH.

How to import the class within the same directory or sub directory?

Python 2

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory".

Then just do...

from user import User
from dir import Dir

The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation. For each level of directory, you need to add to the import path.

bin/
main.py
classes/
user.py
dir.py

So if the directory was named "classes", then you'd do this:

from classes.user import User
from classes.dir import Dir

Python 3

Same as previous, but prefix the module name with a . if not using a subdirectory:

from .user import User
from .dir import Dir

Can not import class from another folder

Check if your project directory is in your system path or not. You can can check it as follows:

import sys

print(sys.path)

Note that when running a Python script, sys.path doesn’t care what
your current “working directory” is. It only cares about the path to
the script. For example, if my shell is currently at the Airflow/
folder and I run python ./dags/mydag.py, then sys.path includes
Airflow/dags/ but NOT Airflow/

If you project directory is not in sys path, you can do following:

  • Include it dynamically.

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

    # import your module now
  • Import all required modules in your project root folder in some file like app.py and then call from here.

Python, can't import file from another folder

You should try

from .a.car import *

The leading dot goes one directory up in folder hierarchy.



Related Topics



Leave a reply



Submit