Thursday, June 23, 2011

Python .ini Module - pyini.py

Last night I was trying to think of things to do, and, of course, making something on the computer was the first thing to pop into my head. Long story short, I decided on making a small .ini module for python. Functionality includes simply reading and writing variables, singly or in dictionaries.


Methods

open(path, [makefile])
Opens a file for use with the pyini module, and returns a pyini object.

pyini.close()
Closes the currently open ini file.

pyini.readVar(var)
Reads the variable 'var' from the currently open ini file, and returns the value.

pyini.readVars()
Reads all variables contained in the currently open ini file, and returns a dictionary object.

pyini.writeVar(var, value)
Writes the variable with name 'var' and value 'value' to the currently open ini file.

pyini.writeVars(dict vars)
Writes the variables contained in the dictionary 'vars' to the currently open ini file.

Attributes

bool pyini.closed
True when no file is currently open.

Code

import os, re
from types import *

class pyini:
   def __init__(self):
      self.closed = True
      
   def open(self, path, makefile=0):
      if not os.path.isfile(path):
         if not makefile:
            raise IOError("No such file: '" + path + "'")
         else:
            if __name__ == "pyini":
               fopen(path, "w").close()
            else:
               open(path, "w").close()
      try:
         if not self.file.closed:
            close()
      except:
         pass
      if __name__ == "pyini":
         self.file = fopen(path, "r+")
      else:
         self.file = open(path, "r+")
      self.closed = False
      return self
      
   def close(self):
      try:
         self.closed = True
         self.file.close()
      except AttributeError:
         pass
         
   def readVar(self, var):
      if self.file.closed:
         raise ValueError("I/O operation on closed file")
      regex = re.compile("^" + var + "=(.*)$", re.IGNORECASE)
      self.file.seek(0)
      for line in self.file:
         linereg = regex.match(line)
         if linereg:
            break
      if linereg:
         return linereg.group(1)
      else:
         raise NameError("variable '" + var + "' is not defined in '" + self.file.name + "'")
      
   def readVars(self):
      if self.file.closed:
         raise ValueError("I/O operation on closed file")
      regex = re.compile("^(.*?)=(.*)$")
      vars  = {}
      self.file.seek(0)
      for line in self.file:
         linereg = regex.match(line)
         if linereg:
            vars[linereg.group(1)] = linereg.group(2)
      return vars
      
   def writeVar(self, var, val):
      if self.file.closed:
         raise ValueError("I/O operation on closed file")
      self.writeVars({var: val})
      
   def writeVars(self, vars):
      if self.file.closed:
         raise ValueError("I/O operation on closed file")
      if not type(vars) == DictType:
         raise TypeError("argument must be of type " + repr(DictType))
      self.file.seek(0)
      iniData = self.file.read()
      iniVars = self.readVars()
      for var, val in vars.iteritems():
         if var in iniVars:
            iniData = re.sub(str(var) + "=.*", var + "=" + str(val), iniData, re.IGNORECASE)
         else:
            iniData = iniData + "\n" + str(var) + "=" + str(val)
      self.file.seek(0)
      self.file.write(iniData)

if __name__ == "pyini":
   fopen = open
   def open(path, makefile=0):
      return pyini().open(path, makefile)

Example

Suppose you have a .ini file with the following contents.

foo=bar
var=hello, world

And used the following code.

import pyini

iniFile = pyini.open("test.ini")
print iniFile.readVar("foo")
print iniFile.readVars()
iniFile.writeVar("foo", "1")
iniFile.writeVars({"var": "hello, world!", "newvar": "This variable is new"})
print iniFile.readVars()

The output would be

bar
{'var': 'hello, world', 'foo': 'bar'}
{'var': 'hello, world!', 'foo': '1', 'newvar': 'This variable is new'}

Download

Mirror 1: Download

No comments:

Post a Comment