pythonvisual-studio-codeimportsys.path

Import from python file located in sub folder


I'm using vs code. I'm running file1.py, it imports a function from file2.py.

The file structure is as follows:

feeds
├── bulk_load
│   ├── __init__.py (empty)
│   └── file2.py
├── __init__.py (empty)
└── file1.py

in file1.py the following works:

from bulk_load.file2 import func123

but the following doesn't:

sys.path.append("bulk_load")
from file2 import func123

Error is

ModuleNotFoundError
No module named file2

I dont really understand why.


Solution

  • You're importing it the wrong way. There's no need to use something like sys.path.append(). bulk_load dir is automatically considered as a module (Python 3.3+), so you should import right from it.

    ./bulk_load/file2.py

    def print_test():
        print("Here we go")
    

    ./file1.py

    from bulk_load.file2 import print_test
    
    print_test()
    

    Run:

    $ python ./file1.py
    Here we go