1

With python I want to transform Joomla ini language files to sql. However the joomla ini files actually misses any section (example: [translations])

Since the rawconfigparser almost does the job but it demands a section, so I construct a temp file with a 'dummy' section named [ALL]:

    fout = tempfile.NamedTemporaryFile(delete=True)
    fin = file(self._inFilename, "r")
    fout.write("[ALL]\n")
    for f in fin.read():
            fout.write(f)
    config = ConfigParser.RawConfigParser(allow_no_value=True)
    config.read(fout.name)
    for c in config.items("ALL"):
            self._ini2sql(unicode(c[0]).upper(), unicode('de'), unicode(c[1][1:-1]))

However... this is def. not the most elegant solution... any tips to make this more pythonic?

Paul
  • 1,068
  • 11
  • 29
  • According to [this question](http://stackoverflow.com/q/2885190/623518) this is seems to be a decent way of doing things. You could improve your solution slightly by using StringIO, as suggested by [this answer](http://stackoverflow.com/a/10746467/623518). Alternatively use [this](http://stackoverflow.com/a/9158109/623518) subclass to `ConfigParser.RawConfigParser`. – Chris Jun 15 '12 at 08:32

3 Answers3

2

You could use a StringIO instead of creating an actual file:

from cStringIO import StringIO
import shutil

data = StringIO()
data.write('[ALL]\n')
with open(self._infilename, 'r') as f:
    shutil.copyfileobj(f, data)
data.seek(0)
config.readfp(data)
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

You can use StringIO instead, which is keeping the content in the RAM:

import cStringIO

fout = cStringIO.StringIO()
fout.write("[ALL]\n")

with open(self._inFilename) as fobj:
    fout.write(fobj.read())
fout.seek(0)

config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(fout)

Please note, there is some optimization in contrast to your code, which is important for you to learn:

  1. Always safely close a file. This is done with the with statement.
  2. You are iterating over each char of the input and writing it. This is not necessary and a serious performance drawback.

As an alternative to ConfigParser I would really recommend the configobj library, which has a much cleaner and more pythonic API (and does not require a default section). Example:

from configobj import ConfigObj

config = ConfigObj('myConfigFile.ini')
config.get('key1') 
config.get('key2') 
schlamar
  • 9,238
  • 3
  • 38
  • 76
  • thnx ms4py, for the learning points AND the alternative solution with ConfigObj which seems indeed much cleaner, I'm gonna check out if ConfigObj is also capable of picking op value's with newlines in it... – Paul Jun 15 '12 at 10:28
0

Reading .ini file in current directory

import configparser
import os

ini_file = configparser.ConfigParser()
ini_file_path = os.path.join(os.path.dirname(__file__),"filename.ini")
ini_file.read(ini_file_path)  # ini_file as a dictionary
print (ini_file["key1"])