Maybe, the module I am writting today is the first Python module I need almost on every new project. It’s not difficult, but it’s tricky! Basicly, config files (the classic .ini files on Windows) are those files where the software store data that it will be use on the next execution. I have always use config files, and that’s the rearon why I learn the first when trying new programming languages.
Pythoning under VB6
Recenty I have a small issue with a librery I use to work with on VB6, so, I decided to write it again. Unconciously, when I finished, I looked at my code and observed that I was using some of the technics I do in Python, and even beter, because I increase functionality with the new version, and with less code. I was modifying my way of programming, even in VB6.
VB6 has no list object, but i was using string arrays “string()“. The truth is that I missed on VB6 the list of Python, but I could handle it!
Using INI files is a two step process: read data, and save data. Normally, you use sentence like this:
- Open an INI file
- Rad “value” from a “key” under a “section”
And for writting:
- Open an INI file
- Save a “value“, attached to a “key” under a “section”
In Python, one librery you can use to deal with config files is ConfigParser, although there is on action that calls my attention, adn I don’t know why this way. The code is:
import ConfigParser parser = ConfigParser.SafeConfigParser() fichero = "write.ini" seccion = 'bug_tracker' clave, valor = 'url', 'http://localhost:8080/bugs' def Guardar(): parser.add_section() parser.set(seccion, clave, valor) sf = open(fichero,"w") # Open the INI file parser.write(sf) sf.close() Guardar()
The issue that calls my attention was that for saving data, first I have to “open” the file (open(fichero,”w”)) instead of doing it inside the module, something like :
If we do it this way, an error will rise!
Reading INI files
For reading data from the config file, it’s very easy and direct:
def Leer(): parser.read(fichero) secciones = parser.sections() if len(secciones)>0: url = parser.get(seccion,clave) print url else: print "No es fichero INI"
To end with, I must admit I like the configParser library, although I expect some one has an improved class, with more options.
Have a nice day.