4

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?

Szymon
  • 633
  • 1
  • 8
  • 28

2 Answers2

3

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]

Community
  • 1
  • 1
Yavar
  • 434
  • 5
  • 13
  • Thx! It's working but I wonder if my solution is better, worse or the same as your? – Szymon Oct 11 '12 at 19:55
  • Looks about the same to me. My only note is that `os.path.join` takes care of joining multiple path components, so you don't really need `os.path.sep`. – Yavar Oct 11 '12 at 20:15
  • It seems that your solution is better. I tested it and it works great and exactly that as I expected. Thank you very much for your help. +1 for you! :-) – Szymon Oct 11 '12 at 20:24
1

it is not finding your config file because you are not using the correct path when called from your mainfile version.

interestingly, configparser silently ignores. check this out:

Python 3.2.3 (default, Sep 10 2012, 18:14:40) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> 
>>> config = configparser.ConfigParser()
>>> config.read('doesnotexist.cfg')
[]
>>> print(config.sections())
[]
>>> 
Corey Goldberg
  • 59,062
  • 28
  • 129
  • 143