How to read properties file in Python? I found ConfigParser() but it has a 'section' limitation, so looking for other alternatives.

Thanks,

Harsh

Recommended Answers

All 13 Replies

You could add a 'mock section' and still use ConfigParser

# tested with python 2.7.2
import ConfigParser
from functools import partial
from itertools import chain

class Helper:
    def __init__(self, section, file):
        self.readline = partial(next, chain(("[{0}]\n".format(section),), file, ("",)))

config = ConfigParser.RawConfigParser(allow_no_value=True)
with open("essconfig.cfg") as ifh:
    config.readfp(Helper("Foo", ifh))
print(config.get("Foo", "old_passwords"))

The config file was

user = mysql
pid-file = /var/run/mysqld/mysqld.pid
skip-external-locking
old_passwords = 1
skip-bdb
skip-innodb

You are a lifesaver; it worked like a charm.

Thanks again,

Harsh

sorry to bother you again but apparently, functools and itertools modules are not there in python 2.2.1. Can you give another version of your program that is compatible with 2.2.1?

This class should work for very old versions of python

class Helper:
    def __init__(self, section, file):
        self.section = "[%s]\n" % section
        self.file = file
        self.state = -1

    def readline(self):
        if self.state:
            if self.state < 0:
                self.state = 0
                return self.section
            else:
                return ""
        else:
            s = self.file.readline()
            if not s:
                self.state = 1
            return s

Why don't you upgrade ? Python 2.2 is a dinosaur :)

Thanks for your quick revert. Much as I'd like to upgrade, this python version is embedded in another product and I've to live with this :(

BTW, can you confirm if below code snippet would also work as it is with older python versions or it merits further changes? I'm getting invalid syntax error here, but seems to be misleading to me.

with open("essconfig.cfg") as ifh:
config.readfp(Helper("Foo", ifh))

Try

try:
    ifh = open("essconfig.cfg", "rb")
    config.readfp(Helper("Foo", ifh))
finally:
    ifh.close()

but I don't know how configparser was in python 2.2.1

Thank-You! seems to be working at first glance.

BTW, would you recommend using stringIO to achieve the same?

BTW, would you recommend using stringIO to achieve the same?

Given that configuration files are often small files, I would say why not ? Loading a small file in memory is not a very expensive operation.

I see you have get good help from Gribouillis.
As a note with open was new in python 2.5.
python 2.2.1 is really old.
Alternatives is to write your own parser that works for your files,it`s not so hard.
If i use config file postet by Grib.

cfg_dict = {}
lst = []
cfg_file = open('essconfig.cfg')
for line in cfg_file:
    if '-' and not '=' in  line:
        line = line.split()
        line.append('None')
        lst.append( line)
    else:
        line = ''.join(line.strip().split('=')).split()
        lst.append(line)
cfg_file.close()

for item in lst:
    cfg_dict[item[0]] = item[1]
print cfg_dict

Test it.

>>> cfg_dict['old_passwords']
'1'
>>> cfg_dict['pid-file']
'/var/run/mysqld/mysqld.pid'
>>> cfg_dict['skip-bdb']
'None'
>>> cfg_dict['user']
'mysql'

Dear Snippsat,

Thanks for responding. For now, my issue is resolvedb by using Gribouillis' suggestions; nevertheless, look forward to continued help from Python gurus on this forum.

Regards,

Harsh

I have created a python module that is almost similar to the Properties class of Java

https://github.com/anandjoshi91/pythonpropertyfileloader

To use this - Copy the properties module in your path/topython/dir/Python34/Lib.

Let's say you have the following properties defined in my_file.properties file

foo = I am awesome
bar = ${chocolate}-bar
chocolate = fudge

Code to load the above properties

from properties import p
prop = p.Property()
prop.load('path/to/my_file.properties')
prop.get('foo') # I am awesome
prop.get('bar') # fudge-bar

@freak_1

Hello, interesting small module, but your install steps are horrible! Never clutter python's own library with your own modules. In order to distribute easily your python modules, you must write a setup.py file. Follow a tutorial such as this one Click Here , which is much simpler than this complete guide for experienced people Click Here

With a setup.py file, the install steps become standardized

  1. dowload the source code
  2. go to the root directory
  3. type python setup.py install

pip install property

It is simple and easy to use. You can find the documentation here.

You may contribute to this project at github.

@Gribouillis. Thanks for your advice. It is much better to distribute the code this way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.