parse a normal textfile

Lie Ryan lie.1296 at gmail.com
Wed Oct 1 13:45:47 EDT 2008


On Wed, 01 Oct 2008 14:09:09 +0200, Tino Wildenhain wrote:

> devi thapa wrote:
>> hi all
>>  
>>            I have one normal text file. I need to parse the file, that
>> too in an associative way .
>> suppose that below is the normal textfile
>> 
>> name='adf'
>> id  =1
>> value=344
>> 
>> 
> there are many approaches to config files. But in your special example,
> it looks like a simplified mapping, so
> 
> parsed=eval("dict(%s)" % ",".join(line
>                               for line
>                               in file("textfile")
>                               if line.strip()
>                                   )
>              )
> 
>  >>> parsed['name']
> 'adf'
> 
> but of course eval() is dangerous, so feel free to explore more then
> this one solution.
> 
> Regards
> Tino

There is no need to use eval on that, you could just use:

f = open('file.conf')
conf = {}
for line in f:
    key, value = line.split('=', 1)
    conf[key] = value

a bit more obscure:

conf = dict(line.split('=', 1) for line in open('file.conf'))




More information about the Python-list mailing list