Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parsing .properties file in Python

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?

like image 525
tshepang Avatar asked May 12 '10 14:05

tshepang


People also ask

How do I read a .properties file in Python?

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.

How read JSON properties file in Python?

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.

How do you update a properties file in Python?

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.


1 Answers

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')] 
like image 75
Alex Martelli Avatar answered Sep 23 '22 08:09

Alex Martelli