Take the 2-minute tour ×

I have a file with the format


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.

share|improve this question
add comment

6 Answers

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)

share|improve this answer
add comment

Maybe ConfigParser can help you.

share|improve this answer
+1 This is likely the best answer for your purposes. –  hughdbrown Oct 22 '10 at 16:22
add comment

Or ConfigObj

share|improve this answer
add comment

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:


VarName="Value"   # if it's a string
# 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

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 :)

share|improve this answer
add comment
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.

share|improve this answer
You can just do for line in f. –  Björn Pollex Oct 22 '10 at 14:32
Yeah, inadverently missed that, thanks. –  user470379 Oct 22 '10 at 14:37
What if value contains '='? =) –  foret Oct 22 '10 at 14:39
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? –  user470379 Oct 22 '10 at 14:46
add comment

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="=" )])
share|improve this answer
I answered another question with a code sample using this sort of approach. stackoverflow.com/a/13019292/742019 –  nacitar sevaht Oct 22 '12 at 20:31
add comment

Your Answer


