[Tutor] config file parsing problem.

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Sep 4 17:10:24 EDT 2003



On Thu, 4 Sep 2003, David Rock wrote:

> > Now, the problem comes when I want to write the (sometimes changed)
> > values back to this file, without over-writing the comments in the
> > file. What's the best way to do this? I thought of creating a
> > dictionary at file-read-time, containing name : line_number pairs, and
> > then writing the (changed) values back to the same line, but it feels
> > kind of kludgey... Is there a better way?  I thought of using reg ex
> > to scan for lines which weren't comments, but then I'd need to
> > identify what the name was, and what line it was on... And I don't
> > know anything about regular expressions.
>
>
> Try using the fileinput module:
>
> http://python.org/doc/current/lib/module-fileinput.html
>
> It has an option for inplace file editing, similar to perl's -i option.


Hi David,


You may also want to try ConfigParser:

    http://www.python.org/doc/lib/module-ConfigParser.html

It does almost exactly what you want, except perhaps not the maintenance
of comments.  I'm not so sure if ConfigParser preserves comments when a
file is saved.  Let's check:

###
>>> from StringIO import StringIO
>>> cfg_file = StringIO("""
... [My Section]
... ## Fill in name here
... name=david rock
... """)
>>> import ConfigParser
>>> p = ConfigParser.ConfigParser()
>>> p.readfp(cfg_file)
>>> p.sections()
['My Section']
>>> p.options('My Section')
['name']
>>> p.get('My Section', 'name')
'david rock'
>>> p.set('My Section', 'answer', '42')
>>> f2 = StringIO()
>>> p.write(f2)
>>> f2.getvalue()
'[My Section]\nanswer = 42\nname = david rock\n\n'
###

Close, but unfortunately, this shows that it doesn't preserves comments.
But I think it's very close to what you're asking for.


Are you commenting individual options?  And how are comments "attached" to
the key-value pairs?  On the same line, or on top?  Perhaps ConfigParser
could be extended to preserve comments that are attached to certain
options.


Tell us a little more about the problem, and perhaps we can see if
ConfigParser can be enhanced to do it.



Good luck to you!




More information about the Tutor mailing list