Python: 解析 INI 风格的配置文件?

Python: Parsing INI-style configuration files?

如何使用 Python 解析 INI 样式的配置文件?有没有可以使用的标准模块?

[section1]
n = 1

[section2]
s = foo

理想情况下,我会得到这样的两级字典:

>>> config
{'section2': {'s': 'foo'}, 'section1': {'n': '1'}}

ConfigParserconfigparser in Python3)为基础,

from ConfigParser import ConfigParser

config = ConfigParser()
config.read('config.ini')

print config.sections()
# ['section1', 'section2']

print config.items('section2')
# [('s', 'foo')]

您可以像这样构建类似 dict 的结构:

config_dict = {}

for section in config.sections():
    config_dict[section] = dict(config.items(section))

print config_dict
# {'section2': {'s': 'foo'}, 'section1': {'n': '1'}}

从标准库中查看 configparser

我从 INI 文件中写了一个简单的 class 到 read/write。如果您不想依赖外部库,可以用常规词典替换 "odict" 位。注意:此代码针对 python 2.7.

进行了测试
from collections import OrderedDict as odict
import sys

class IniFile(object):
    def __init__(self,fn=None):
        self.fn = fn
        self.top = odict()
        self.sections = odict()
        if fn: self.read()
    def read(self,fn=None):
        fn = fn or self.fn
        assert fn
        handle = open(fn)
        current = self.top
        for line in handle.readlines():
            try:
                stripped = line.strip()
                if stripped.startswith(";"): continue
                if "#" in stripped:
                    where = stripped.find("#")
                    if where == 0: continue
                    stripped = stripped[0:where]
                if "=" in stripped:
                    k,v = stripped.split("=",1)
                    current[k.strip()] = v.strip()
                elif stripped.startswith("[") and stripped.endswith("]"):
                    inside = stripped[1:-1]
                    current = self.sections.setdefault(inside,odict())
            except Exception,e:
                print >>sys.stderr,"problem with:"
                print >>sys.stderr,line
                raise
        handle.close()
    def write(self,fn=None):
        if fn is None: fn = self.fn
        if fn is None: raise Exception("please specify a filename!")
        handle = open(fn,"w")
        for key,value in self.top.items():
            handle.write("%s=%s\n" % (key,value))
            handle.flush()
        for name,content in self.sections.items():
            handle.write("[%s]\n" % name)
            handle.flush()
            for key,value in content.items():
                handle.write("%s=%s\n" % (key,value))
                handle.flush()
        handle.close()
        return fn