Search code examples
pythonpython-3.xconfigurationrelative-path

How to read file content from the relative path in config file


I have a config file & in which, data_2 content is huge JSON objects, so i have mentioned the relative path of the file as:

    Test.ini

    [COMMON]
    data_1 =Hello
    data_2 =c:/.../data.txt

How to read the 'data.txt 'file content in python.

Initial config in python as :

   try:
      from configparser import ConfigParser
   except ImportError:
      from ConfigParser import ConfigParser  # ver. < 3.0
   config = ConfigParser()
   config.read('test.ini')

  for x in range(1,6):
      data = config.get('COMMON', f'data_{x}')
      print(data)

for print operation:

     data_1 = Hello  # get printed
     data_2 = c:/.../data.txt # get printed instaed of data.txt file content.

Solution

  • You will need to open the file and read it (or even parse it if it's a JSON):

    import json
    
    # ...
    
    # First retrieve the value in the config then
    
    # ...
    
    with open(data_2, "r") as f:
      json_data = json.load(f)
    
    # ...