Search code examples
pythonconfigparser

Python,ConfigParser-Referencing in earlier directory


In my downloads folder, I have a folder called bin. Within the folder bin I have a file called config_template.ini, and another folder called SN. Within the folder SN I have a file called sample.py. In sample.py I use:

config = configparser.ConfigParser()
config.read('config_template.ini')

Since 'config_template.ini' is not in the same folder, how would I reference it?

This is the file address of sample.py:

C:\Users\user1\Downloads\bin\SN\sample.py

This is the file address of the config_template file.

C:\Users\user1\Downloads\bin\config_template.ini

Any help would be appreciated!


Solution

  • Use the absolute path:

    config.read(r'C:\Users\user1\Downloads\bin\config_template.ini')
    

    Note the r in front of the string, so the \ does not need to be escaped.

    Or more fancy, go up one path from where your python file is:

    import os
    inifile = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'config_template.ini'))
    config.read(inifile )