在python中解析config.ini

时间:2016-07-14 09:41:30

标签: python parsing config

文件

  

的config.ini

文件     ; SQL Server 2012配置文件     [OPTIONS]

; Specifies a Setup work flow, like INSTALL, UNINSTALL, or UPGRADE. This is a required parameter. 

ACTION="Install"

; Detailed help for command line argument ENU has not been defined yet. 

ENU="True"

; Parameter that controls the user interface behavior. Valid values are Normal for the full UI,AutoAdvance for a simplied UI, and EnableUIOnServerCore for bypassing Server Core setup GUI block. 


IACCEPTSQLSERVERLICENSETERMS="True"

; Setup will not display any user interface. 

QUIET="True"

我有一个像这样的python代码

def change_file(filepath, add_comment, trigger_words):

    def process(line):
        line_word = line.lstrip(';').split('=')[0]

        if line_word in trigger_words:
            if add_comment:
                line = line if line.startswith(';') else ';' + line
            else:
                line = line.lstrip(';')

        return line


    with open(filepath) as f:
        content = [process(line) for line in f]


    with open(filepath, 'r+') as f:
        f.truncate()
        f.write(''.join(content))


change_file('abc.ini', add_comment=True, trigger_words=["IACCEPTSQLSERVERLICENSETERMS", "ENU"])

当我运行上面的代码时,我得到像这样的输出

;SQL Server 2012 Configuration File
    ਍嬀伀倀吀䤀伀一匀崀ഀഀ

    ਍㬀 匀瀀攀挀椀昀椀攀猀 愀 匀攀琀甀瀀 眀漀爀欀 昀氀漀眀Ⰰ 氀椀欀攀 䤀一匀吀䄀䰀䰀Ⰰ 唀一䤀一匀吀䄀䰀䰀Ⰰ 漀爀 唀倀䜀刀䄀䐀䔀⸀ 吀栀椀猀 椀猀 愀 爀攀焀甀椀爀攀搀 瀀愀爀愀洀攀琀攀爀⸀ ഀഀ

    ਍䄀䌀吀䤀伀一㴀∀䤀渀猀琀愀氀氀∀ഀഀ

    ਍㬀 䐀攀琀愀椀氀攀搀 栀攀氀瀀 昀漀爀 挀漀洀洀愀渀搀 氀椀渀攀 愀爀最甀洀攀渀琀 䔀一唀 栀愀猀 渀漀琀 戀攀攀渀 搀攀昀椀渀攀搀 礀攀琀⸀ ഀഀ

    ਍䔀一唀㴀∀吀爀甀攀∀ഀഀ

    ਍㬀 倀愀爀愀洀攀琀攀爀 琀栀愀琀 挀漀渀琀爀漀氀猀 琀栀攀 甀猀攀爀 椀渀琀攀爀昀愀挀攀 戀攀栀愀瘀椀漀爀⸀ 嘀愀氀椀搀 瘀愀氀甀攀猀 愀爀攀 一漀爀洀愀氀 昀漀爀 琀栀攀 昀甀氀氀 唀䤀Ⰰ䄀甀琀漀䄀搀瘀愀渀挀攀 昀漀爀 愀 猀椀洀瀀氀椀攀搀 唀䤀Ⰰ 愀渀搀 䔀渀愀戀氀攀唀䤀伀渀匀攀爀瘀攀爀䌀漀爀攀 昀漀爀 戀礀瀀愀猀猀椀渀最 匀攀爀瘀攀爀 䌀漀爀攀 猀攀琀甀瀀 䜀唀䤀 戀氀漀挀欀⸀ ഀഀ

    ਍ഀഀ
    IACCEPTSQLSERVERLICENSETERMS="True"
    ਍ഀഀ
    ; Setup will not display any user interface.
    ਍ഀഀ
    QUIET="True"

期望只是添加

  

这些话的前面

  

“IACCEPTSQLSERVERLICENSETERMS”,“ENU”

1 个答案:

答案 0 :(得分:2)

如果它是真正的INI文件,那么您可以使用名为configparser的Python标准库模块。

否则,将文件读入内存并将其拆分为字典或列表。

然后你可以添加你想要的任何东西并把它放回去。

像这样:

def LoadConfigFile (path):
    f = open(path, "r")
    c = f.readlines()
    f.close()
    d = {}
    for x in c:
        x = x.strip()
        if x.startswith(";") or x.startswith("#"): continue
        x = x.split("=", 1)
        if len(x)!=2: continue
        d[x[0].rstrip()] = x[1].lstrip()
    return d

通过这种方式,您可以轻松访问名称,值对,并且可以随时添加选项。

如果您想保存它,只需撤消该过程。

如果您希望选项按原始顺序排序,请使用OrderedDict()或列表而不是字典。