max max - 1 month ago 11
Python Question

reading and writing cfg files in python

I am trying to read and write cfg files in python.
I've tried the package called configparser but it complains about missing headers because apparently it does not understand the format of my file.
I would like to know your opinion on this to accomplish this as easily as possible. Note: I need to stick with this format.

Here is the format of my file:

PROFILE_PERIODS =
( // note that this is not a curly brace
{ //comment
PRIORITY = 1;
},

{ //comment
DESCRIPTION = "drgdfth";
}
)
TIME_SYNCHRONIZATION =
{
INTERVAL = 100;
}


This config file is also read by a c library called libconfig.
Thanks

Answer

Your file looks like it has libconfig format, which is reasonably common in the C/C++ world.

I've written python-libconf, a pure-Python libconfig file reader/writer. The interface is borrowed from the json standard library module. It's pretty simple:

import libconf
with io.open('file.cfg', encoding='utf-8') as f:
    cfg = libconf.load(f)

It can be installed easily via pip (pip install libconf) and works well in virtual environments. Compared to other Python libconfig readers, it is both permissively licensed (MIT) and pure-Python (no C modules to compile).

Comments