Simple ini Config parser examples needed

Glenn Linderman v+python at g.nevcal.com
Tue Dec 2 22:47:59 EST 2008


On approximately 12/2/2008 3:22 PM, came the following characters from 
the keyboard of Chris Rebert:
> On Tue, Dec 2, 2008 at 2:51 PM, Glenn Linderman <v+python at g.nevcal.com> wrote:
>   
>> On approximately 12/2/2008 1:31 PM, came the following characters from the
>> keyboard of Chris Rebert:
>>     
>>> On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN <rbrennan55 at hotmail.com>
>>> wrote:
>>>
>>>       
>>>> Hello,
>>>>
>>>> I have a very simple ini file that I needs parsed.  What is the best way
>>>> I
>>>> can parse an ini file that doesn't include sections?
>>>>         
>
> *Bangs head against wall repeatedly*
> I merely glossed the question and missed that all-important second
> sentence! fsck!
> My apologies, I shouldn't write email before having coffee :)
> Fortunately Tim followed quickly with the correct answer to the OP.
>   

Tim provided a correct-looking answer, albeit somewhat complex, as it 
doesn't reuse the logic in the ConfigParser.  That's why I suggested yet 
another alternative, yet left one key item off myself (added below).

>>>> As in:
>>>>         
>>> Since it appears that ConfigParser requires at least one section
>>> header, I'll assume the file starts with the following line:
>>>
>>> [main]
>>>
>>>       
>>>> person=tall
>>>> height=small
>>>> shoes=big
>>>>
>>>>
>>>> Thats it.  Can anyone help me?
>>>>
>>>>         
>>> Completely untested:
>>>
>>> import ConfigParser
>>> config = ConfigParser.RawConfigParser()
>>> config.readfp(open("path/to/file.cfg"))
>>> config.get("main", "height") #==> "small"
>>>
>>> Cheers,
>>> Chris
>>>
>>>       
>> Of course the OP question was that the line you assume isn't there.  But if
>> the ini is simple, maybe it is short enough to read into a string, then
>> prepend the line, then parse with ConfigParser.
>>     

And I meant to add "parse with ConfigParser by passing the combined 
string in via StringIO.

-- 
Glenn -- http://nevcal.com/
===========================
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking




More information about the Python-list mailing list