Link to home
Start Free TrialLog in
Avatar of rj2
rj2

asked on

Read everything from a Windows .ini file

Hello!
Is is possible to read all entries from a Windows .ini file in Python, also if you don't know exactly the names of sections and values? (see sample .ini file below). I would like to have some generic code that can read all sections and values, whatever they are.

[Section1]
Entry1=test
Entry2=test2

[Section2]
debug=1
Name=test
Avatar of Glowingdark
Glowingdark

Its a bit ugly, but it works.

# parse ini file
myfile = open('c:\sample.ini', 'r')
sections = []
keysandvalues = []

lines = []
lines = myfile.readlines()
myfile.close()
section = 'no section'

for line in lines:
    if line[0:1] == "[":
        if len(keysandvalues) > 0:
            # new section
            sections.append([section, keysandvalues])
            section = line.strip()
            keysandvalues = []
        elif section <> 'no section':
            #empty section
            sections.append([section, []])
            section = line.strip()
        else:
            # first section
            section = line.strip()
    elif line.find('=') > 1:
        #key value pair
        key, value = line.split('=')
        keysandvalues.append([key.strip(),value.strip()])
    else:
        pass

# last section
sections.append([section, keysandvalues])
   
the [sections]  will still have their brackets around them, and I dont like manually appending the last section, but it works

Kevin
Avatar of F. Dominicus
Use the module ConfigParser
http://www.python.org/doc/current/lib/module-ConfigParser.html

Regards
Friedrich
Avatar of rj2

ASKER

fridom,
Do you got a sample that demonstrates this?
(read all values from ini file and prints out their values using the module ConfigParser?)
ASKER CERTIFIED SOLUTION
Avatar of F. Dominicus
F. Dominicus
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial