Solved

Read everything from a Windows .ini file

Posted on 2004-04-02
4
8,345 Views
Last Modified: 2007-12-19
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
0
Comment
Question by:rj2
  • 2
4 Comments
 
LVL 2

Expert Comment

by:Glowingdark
ID: 10742683
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
0
 
LVL 24

Expert Comment

by:fridom
ID: 10746725
Use the module ConfigParser
http://www.python.org/doc/current/lib/module-ConfigParser.html

Regards
Friedrich
0
 
LVL 10

Author Comment

by:rj2
ID: 10813306
fridom,
Do you got a sample that demonstrates this?
(read all values from ini file and prints out their values using the module ConfigParser?)
0
 
LVL 24

Accepted Solution

by:
fridom earned 250 total points
ID: 10820385
Have you read the API description? Here's your .cfg file:
[Section1]
Entry1=test
Entry2=test2

[Section2]
debug=1
Name=test

here's a code to print it.
import ConfigParser

cp = ConfigParser.ConfigParser()
cp.readfp (open('config.cfg'))

for section in cp.sections():
    print (section)
    for item in cp.items(section):
        print ("key = " + item[0] + " value = " + item[1])


Ausgabe:
Section2
key = debug value = 1
key = name value = test
Section1
key = entry2 value = test2
key = entry1 value = test

Friedrich
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to play a bell/system sound in Mac using Python 1 333
Error catching in Python 8 48
Use of python .format to prefill  form. 5 63
windows 10 bash shell 4 43
Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now