0

I'm currently in the 'strategy.py' file and I'm trying to import 'utils.py' and 'BaseStrategy.py' ('utils.py' is a file with some functions in it, 'BaseStrategy.py' contains a class with the name 'BaseStrategy').

Folder structure:

program\
  __init__.py
  main.py
  folder1\
    __init__.py
    utils.py
    BaseStrategy.py
  folder2\
    __init__.py
    strategy.py

In 'main.py' I'm able to import both files like this:

from folder1.BaseStrategy import BaseStrategy
from folder1 import utils

So how can I import 'utils.py' and 'BaseStrategy.py' in 'strategy.py'?

Kobe Janssens
  • 310
  • 2
  • 13
  • Does this answer your question? [Importing files from different folder](https://stackoverflow.com/questions/4383571/importing-files-from-different-folder) – Gamopo Jan 26 '21 at 12:34
  • @iqmaker Can you explain it to me by using a folder structure? – Kobe Janssens Jan 26 '21 at 12:36

3 Answers3

1
import sys    
sys.path.insert(0, 'program/folder1')
from folder1 import utils
from folder1 import BaseStrategy

You can also change the:

sys.path.insert(0, 'program/folder1')

To:

sys.path.append('../')

But it will mess up with the import from your parent directory (main.py). However you can overcome that with :

import os,sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
Younes
  • 391
  • 2
  • 9
0

Essentially, you need to put a blank file named __init__.py in the subdirectory. If you want to take a look at the documentation you can do so here (6.4).

MF-
  • 185
  • 8
0

find:

./main/
./main/folder2
./main/folder2/__init__.py
./main/folder1
./main/folder1/base.py
./main/folder1/__init__.py
./main/__init__.py

cat ./main/folder1/base.py

import sys
import os
sys.path.append(os.getcwd() + '/..')

import folder2
iqmaker
  • 2,162
  • 25
  • 24