[Tutor] config file parsing problem.

David Rock david at graniteweb.com
Thu Sep 4 17:39:58 EDT 2003


* Thomi Richards <thomi at imail.net.nz> [2003-09-03 22:54]:
> 
> Hi guys,
> 
> 
> What's the best way to read / write a config file? More specifically:
> 
> I have a config file with a series of name = value pairs. This file also has 
> comments (line which *start* with a "#" or a ";") amongst the actual data 
> lines. At the moment, I am just opening the file, reading it line by line, 
> and either ignoring it, or exec()ing the line (I know this isn't very safe, 
> but for now it's OK).
> 
> 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.

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20030904/aac14bd9/attachment.bin


More information about the Tutor mailing list