I've got a text file in the format
key1=value1
key2=value2
key3=value3
What would be the best way to read it in so I have access to the values in a form like myObject.key1
or myObject["key1"]
?
I've got a text file in the format
key1=value1
key2=value2
key3=value3
What would be the best way to read it in so I have access to the values in a form like myObject.key1
or myObject["key1"]
?
Something like this:
myObject = {}
with open("something.ini") as f:
for line in f.readlines():
key, value = line.rstrip("\n").split("=")
myObject[key] = value
Note that, as @Goodies mentioned below, if you assign to the same key multiple times, this will just take the last value. It is however trivial to add some error handing:
myObject = {}
with open("something.ini") as f:
for line in f.readlines():
key, value = line.rstrip("\n").split("=")
if(not key in myObject):
myObject[key] = value
else:
print "Duplicate assignment of key '%s'" % key
The classic one liner ...
x = dict((kv.split('=') for kv in (l.strip('\n') for l in open('hello.txt'))))
Which results in:
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
I would use a dictionary if I were you. Try this if your application accept the use of dictionaries.
with open('your_file_name') as f:
content = f.readlines()
myDict = {}
for line in content:
a, b = line.split('=')
myDict += {a:int(b)}
You could do it with regular expressions
import re
with open('/path/to/file', 'r') as f:
matches = re.findall(r'^(.+)=(.*)$', f.read(), flags=re.M)
d = dict(matches)
print d['key']
Be aware that if you have duplicate keys in your file, the last one found is going to shadow the others.
If you want to be able to do d.key3
, you can use the bunch
package
from bunch import Bunch
d = Bunch(matches)
print d.key3