Search code examples
pythonimportmodulepython-3.xconfigparser

How to read config file from module and from main file?


I've a problem with loading and reading my config file. When I running the imptest.py file then Python read configfile.cfg and I get following output:

D:\tmp\test\dir1>python imptest.py
Section1
Section2
Section3

But when I running the mainfile.py file then nothing happens and seems that Python don't read the configfile.cfg file:

D:\tmp\test>python mainfile.py

D:\tmp\test>

My structure of directories:

test/
 dir1/
    __init__.py
    imptest.py
 static/
    configfile.cfg
 mainfile.py

Source of mainfile.py file:

from dir1.imptest import run

if __name__ == '__main__':
    run() 

Source of imptest.py file:

import configparser

def run():
    config = configparser.ConfigParser()
    config.read('../static/configfile.cfg', encoding='utf8')

    for sections in config.sections():
        print (sections)

if __name__ == '__main__':
    run()

Source of configfile.cfg file:

[Section1]
Foo = bar
Port = 8081

[Section2]
Bar = foo
Port = 8080

[Section3]
Test = 123
Port = 80 

Edited

So far my solution (absolute paths) is:

cwd = os.path.realpath(os.path.dirname(__file__) + os.path.sep + '..')
config.read(os.path.join(cwd,'static' + os.path.sep + 'configfile.cfg'), encoding='utf8')

Is it better, worse or the same as solution by @Yavar?


Solution

  • If you want a relative path to imptest.py, use __file__:

    mydir = os.path.dirname(os.path.abspath(__file__))
    new_path = os.path.join(mydir, '..', rest_of_the_path)
    

    Also, see the answers to this question: Difference between __file__ and sys.argv[0]