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