views:

105

answers:

6

I have a file with the format

VarName=Value
.
.

I want to read it into a hash such that H("VarName") will return the value.

What would be a quick way? (read a set of strings, split all of them where the equality sign is, and then put it into a hash?

I am working with python.

+1  A: 
d = {}
with open('filename') as f:
    for line in f:
        key, value = line.split('=')
        d[key] = value

Edit: As suggested by foret, you could change it to

    for line in f:
        tokens = line.split('=')
        d[tokens[0]] = '='.join(tokens[1:])

which would handle the case where equals signs were allowed in the value, but would still fail if the name could have equals signs as well -- for that you would need a true parser.

You can just do `for line in f`.
Space_C0wb0y
Yeah, inadverently missed that, thanks.
What if value contains '='? =)
foret
Then either you need a full-on parser for lines like `'x=y'="\"'z'=a\""` or if you can't quote parts the file format is ambiguous: does `x=y=z` mean `x -> y=z` or `x=y -> z`?
+1  A: 

Or ConfigObj

Mark
+5  A: 

Maybe ConfigParser can help you.

rubik
+1 This is likely the best answer for your purposes.
hughdbrown
A: 

The csv module will let you do this easily enough:

import csv
H = dict([(row[0], row[1]) for row in csv.reader(open("the_file", "r"), delimiter="=" )])
GreenMatt
+1  A: 

The oneliner answer:

H = dict(line.strip().split('=') for line in open('filename.txt'))

(optionally use .split() with maxsplit=1 if the values could also contain the "=" character)

Steven
+1  A: 

this may be a stupid answer but who know maybe it can help you :)

change the extension of your file to .py, and do necessary change like this:

file.py

VarName="Value"   # if it's a string
VarName_2=1
# and you can also assign a dict a list to a var, how cool is that ?

and put it in your package tree or in sys.path, and now you can call it like this in the script when you want to use it:

>>> import file
>>> file.VarName
'Value'

why i'm writing this answer it's because ,what the hell is this file ? i never see a conf file like this , no section no nothing ? why you want to create a config file like this ? it look like a bad config file that should look like the Django settings, and i prefer using a django setting-like config file when ever i can.

Now you can put your -1 in the left :)

singularity