0
dir1\
    __init__.py
    config.py

dir2\
    __init__.py
    module1.py

In order to protect sensitive config settings, I have a file config.py in let's say dir1. I have dir2 that has the main Python files.

I want all the modules in dir2 to be able to access config.py. So I thought to import it once inside __init__.py that is inside dir2.

How do I do this? I tried putting this inside __init__.py in dir2:

# __init__.py in dir2

import os
import sys

config_dir = os.path.join(os.environ['userprofile'],'Path','To','dir1')
sys.path.append(config_dir)

from dir1 import config

I put this in module1.py

# module1.py
from config import USERS

but when I run module1 I get:

ModuleNotFoundError: No module named 'config'.

Josh D
  • 794
  • 4
  • 14
  • 31

2 Answers2

0

The directory with the import needs a __init__.py file even if it's empty. This is so the Python Interpreter can recognise that it is a module and is therefore importable.

Bart Van Loon
  • 1,430
  • 8
  • 18
Stuart Buckingham
  • 1,574
  • 16
  • 25
0

Have a look at this answer:

Importing files from different folder

I think you already found the solution, you just have to put the code that you placed in dir2/__init__.py in module1.py and every other module in which you want to use files from dir1.

As far as I understand, the __init__.py file is just for python to recognize the folder, but not for actual initialization code for a project.

Lukas Ansteeg
  • 332
  • 2
  • 13