Read the file with the format "variable = value" (Windows INI)?

I am learning Python and as a starter developer, I have few questions.

I need to read a file with this format:

# This is the text file
[label1]
method=auto

[label2]
variable1=value1
variable2=ae56d491-3847-4185-97a0-36063d53ff2c
variable3=value3

Now I have the following code:

# This is the Python file
arq = open('desiredFile').read()
index = arq.rfind('variable1=')
(??)

But I really don't know how I can continue. My goal is to read the value before a new line appears. I believe that the indices are counted between "id =" and the new line, so we get the text inside these indices, but I do not know how to do this in Python. To summarize, I want to save the values ​​of [label2] in Python variables:

pythonVariable1 = <value of variable1 in [label2]>
pythonVariable2 = <value of variable2 in [label2]>
pythobVariable3 = <value of variable3 in [label2]>

Note that pythonVariable2 is "ae56d491-3847-4185-97a0-36063d53ff2c" and the variables inside the text file have a unique name. So how can I store the values ​​of these variables in Python variables?

+4
1

configparser module . ( Windows INI).

try:
    # Python 3
    from configparser import ConfigParser
except ImportError:
    # Python 2
    from ConfigParser import ConfigParser

config = ConfigParser()
config.readfp( open( 'desiredFile' ) )

somevar = config.get( 'label2', 'variable1' )
+10

All Articles