faqts : Computers : Programming : Languages : Python : Modules

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 13 people (54%) answered Yes
Recently 5 of 7 people (71%) answered Yes

Entry

How can I use the ConfigParser to parse through a text file?

Jul 12th, 2003 22:24
Karl Dubost, Sumita Ponnuchamy, http://www.faqts.com/knowledge_base/community/index.phtml/id/16445


Imagine a file  'MyConfig.cfg' with for Content
# This is Myconfig File
[PersonalData]
FirstName: John
LastName: Smith
[Directories]
Home: /home/smith/
Root:   /root
# End of the file
As you can see the files can take
 * '#'  or ';' for comments
 * [sections] sections of the config file
 * Variable: Value  for the couples variable = value
Now your program will be like that:
#!/usr/bin/python
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open('MyConfig.cfg'))
# get a list of sections
print "+ Sections List:", config.sections()
# get a list of Variables for a section
print "+ Section PersonalData:", config.options('PersonalData')
# get a particular value of a variable inside a section
print "+ Value of Home Dir", config.get('Directories','Home')