Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

file

I'm learning Python and as a starter developer I have few questions.

I need read a file that have 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 objective is read the value until a new line comes. I think in count the indices between "id=" and the new line, so get the text inside this indices, but I don't have any idea how to do this in Python. Summarizing I want store 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 equals to "ae56d491-3847-4185-97a0-36063d53ff2c" and variables inside the text file have a unique name. So, how can I store the values of this variables in Python variables?

like image 959
Paladini Avatar asked Dec 25 '22 19:12

Paladini


1 Answers

Use the configparser module to handle this instead. That module parses this file format ( called the Windows INI format ) directly.

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' )
like image 97
Martijn Pieters Avatar answered Dec 28 '22 10:12

Martijn Pieters