aboutsummaryrefslogtreecommitdiffstats
path: root/examples/iniparser.py
blob: 9b0cf2360d4244a06f932419d2a5f59ee8907d42 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/usr/bin/python
import os
import sys
import time

class IniParser():

    def getValue(self, inifile, section, var):
        if os.path.isfile(inifile):
            with open(inifile, "r") as cfgfile:
                content = cfgfile.read()
            content = content.split("\n")
            for i in xrange (len(content)-1):
                if "["+section+"]" in content[i]:
                    j = i+1
                    while not "[" in content[j]:
                        if var == content[j].split("=")[0]:
                            return content[j].split("=")[1].replace('"','').strip()
                        else:
                            j += 1
            cfgfile.close()

    def setValue(self, inifile, section, var, value):
        if os.path.isfile(inifile):
            with open(inifile, "r") as cfgfile:
                content = cfgfile.read()
            content = content.split("\n")
            for i in xrange (len(content)-1):
                if "["+section+"]" in content[i]:
                    j = i+1
                    while not "[" in content[j]:
                        if var == content[j].split("=")[0]:
                            content[j] = var + '="' + value +'"'
                            break
                        else:
                            j += 1
            cfgfile.close()
            with open(inifile, "w") as cfgfile:
                cfgfile.write("\n".join(content))

#inifile = IniParser()

#print inifile.getValue("test.ini", "section3", "var3")