1

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"]?

Bob Roberts
  • 151
  • 1
  • 6
  • 4
    I wonder if [configparser](https://docs.python.org/3.5/library/configparser.html) would be useful here... I've never used it myself. – Kevin Feb 09 '16 at 17:43
  • Oh, yes. configparser is a *very* helpful module. You can have `key=value` or `key:value`. – zondo Feb 09 '16 at 17:47
  • 1
    configparser could be useful but only if you are able do reformat the text file a bit. The text file has to look a bit different... In particular afaik you need to define some sections... – Stefan Reinhardt Feb 09 '16 at 17:47
  • Possible duplicate of [Parse key value pairs in a text file](http://stackoverflow.com/questions/9161439/parse-key-value-pairs-in-a-text-file) – Andy Feb 09 '16 at 17:48

4 Answers4

5

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
Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • Almost too simple and works. Keep in mind that if you have a duplicate, it will take the last value. – Goodies Feb 09 '16 at 17:51
3

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'}
mementum
  • 3,153
  • 13
  • 20
1

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)}
Roger Hache
  • 405
  • 1
  • 5
  • 17
0

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
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118