0

I have the following directory:

  • IoT [Folder]
    • DC [Folder]
      • main.py
      • config.ini

inside main.py I have:

config.read('config.ini')

which works perfect if I run my python script after doing cd .....IoT/DC

But it doesn't work once I run my python script directly from IoT folder, how can I solve this?

I can't know from which folder my program will be run...

If I have to choose one I prefer running it directly from IoT like this:

python3 DC/main.py
Algo
  • 11
  • 4

2 Answers2

0
from os import getcwd
from os.path import join

config_file_path = join(getcwd(), 'conf', 'config.ini')
Matteo Pasini
  • 1,787
  • 3
  • 13
  • 26
0

Paths are relative to the current working directory, which is usually the directory from which you run your program (but the current directory can be changed by your program [or a module] and it is in general not the directory of your program file).

You can do something like this

import os
config.read(os.path.join(os.path.dirname(__file__), 'DC', 'config.ini'))

References : https://www.geeksforgeeks.org/__file__-a-special-variable-in-python/

SRJ
  • 2,092
  • 3
  • 17
  • 36