The ConfigParser
module raises an exception if one parses a simple Java-style .properties
file, whose content is key-value pairs (i..e without INI-style section headers). Is there some workaround?
Reading Properties File in Python The first step is to import the Properties object into our Python program and instantiate it. The next step is to load the properties file into our Properties object. Now, we can read a specific property using get() method or through the index.
Reading From JSON Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.
This should help. from configobj import ConfigObj config = ConfigObj("FileName") print(config['hostKey']) config['hostKey'] = "updatedValue" #Update Key config. write() #Write Content print(config['hostKey']) #Check Updated value.
Say you have, e.g.:
$ cat my.props first: primo second: secondo third: terzo
i.e. would be a .config
format except that it's missing a leading section name. Then, it easy to fake the section header:
import ConfigParser class FakeSecHead(object): def __init__(self, fp): self.fp = fp self.sechead = '[asection]\n' def readline(self): if self.sechead: try: return self.sechead finally: self.sechead = None else: return self.fp.readline()
usage:
cp = ConfigParser.SafeConfigParser() cp.readfp(FakeSecHead(open('my.props'))) print cp.items('asection')
output:
[('second', 'secondo'), ('third', 'terzo'), ('first', 'primo')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With