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
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
Use the module ConfigParser
http://www.python.org/doc/current/lib/module-ConfigParser.html
Regards
Friedrich
http://www.python.org/doc/current/lib/module-ConfigParser.html
Regards
Friedrich
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?)
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
# 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.
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