Paul
Paul

Reputation: 1066

python reading ini files

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?

Upvotes: 1

Views: 715

Answers (3)

user11766756
user11766756

Reputation:

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"])

Upvotes: 0

schlamar
schlamar

Reputation: 9511

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') 

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318488

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)

Upvotes: 2

Related Questions