Search code examples
pythonpropertiesconfigconfigparser

how to access properties stored in a .properties file in a python file using ConfigParser


I have a .properties file which contains data. I am trying to access these properties from a python file.

My properties file looks something like this:

[section1]
header = time, date, name, process_name, location

[section2]
content = timestamp, details

I am using ConfigParser in python and I wanna access the properties like that:

config.get("section1", header[0])
config.get("section2", content[2])

But right now, I am getting this error: " global name 'header' is not defined "

How do I resolve this error or how do I go about using the position number to reference the particular property ?


Solution

  • config.get('section1', 'header') will return 'time, date, name, process_name, location'. Then you use split to break it down into ['time', 'date', 'name', 'process_name', 'location'].

    print(config.get('section1', 'header').split(', ')[0])
    # time
    
    print(config.get('section2', 'content').split(', ')[1])
    # details