Fork me on GitHub

jprops by mgood

Java properties file parser

Installation

Use pip to install jprops from PyPI.

pip install jprops

Usage

Reading properties

Use jprops.load_properties to read a properties file and return a normal Python dict.

import jprops
with open('mine.properties') as fp:
  properties = jprops.load_properties(fp)
You can provide a custom "mapping" to load the properties into a different data strucuture. For example, if you would like to keep the properties in the same order they originally appeared, you can use an "ordered dict", such as collections.OrderedDict from Python 2.7, or brownie.OrderedDict. The "mapping" can be any type or function that accepts an iterable of (key, value) pairs.
import collections
with open('mine.properties') as fp:
  properties = jprops.load_properties(fp, collections.OrderedDict)
load_properties is just a wrapper to iter_properties, which you can use directly if you want to process the properties lazily without loading them all into a data structure.
with open('mine.properties') as fp:
  for key, value in jprops.iter_properties(fp):
    if key.startswith('foo'):
      print key, value

Writing properties

Use jprops.store_properties to write a dict, dict-like object, or any iterable of (key, value) pairs to a file.

x = {'y': '1', 'z': '2'}
with open('out.properties', 'w') as fp:
  jprops.store_properties(fp, x)

By default jprops follows the Java convention of writing a timestamp comment to the beginning of the file, like:

#Thu Oct 06 19:08:50 EDT 2011
y=1
z=2
You can suppress writing the timestamp comment by passing timestamp=False.

You can provide a custom header comment that appears before the timestamp. Multi-line comments are handled appropriately, continuing the comment across lines.

jprops.store_properties(fp, {'x': '1'}, comment='Hello\nworld!')
#Hello
#world!
#Thu Oct 06 19:17:21 EDT 2011
x=1

You can also use write_comment and write_property to have finer-grained control over writing a properties file.

with open('out.properties', 'w') as fp:
  jprops.write_comment(fp, 'the hostname:')
  jprops.write_property(fp, 'host', 'localhost')
  jprops.write_comment(fp, 'the port number:')
  jprops.write_property(fp, 'port', '443')
#the hostname:
host=localhost
#the port number:
port=443

Important notes for Python 3

jprops expects bytes when decoding the property file, so with Python 3 you'll need to use open(filename, 'rb') to open the property file in binary mode (or use the mode 'wb' to open for writing)

Authors

Matt Good (matt@matt-good.net)

Download

You can download this project in either zip or tar formats.

You can also clone the project with Git by running:

$ git clone git://github.com/mgood/jprops