简体   繁体   中英

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

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?

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' )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM