【问题标题】:How to change order of sections in INI files with Python?如何使用 Python 更改 INI 文件中部分的顺序?
【发布时间】:2019-07-14 15:22:22
【问题描述】:

我想根据节的其中一个键中的数值对 .ini 文件中的节进行排序。

我尝试使用此处描述的 OrderedDict 方法,但它对我不起作用,(Define order of config.ini entries when writing to file with configparser?)。

INI 文件:

[DATA] 
datalist = ALL, cc, ch

[DATA.dict]

[DATA.dict.ALL] 
type = Default 
from = 748.0 
to = 4000.0 
line = 0

[DATA.dict.cc] 
type = Energy 
from = 3213.9954023 
to = 3258.85057471 
line = 1

[DATA.dict.ch] 
type = Energy 
from = 1127.11016043 
to = 1210.58395722 
line = 2 

目标是按'from'值对部分进行排序并更改行值以匹配该值,即'h'部分应更改为line = 1并向上移动。

我编写了代码来列出“from”值并根据该顺序更改“line”值。我还得到了将“datalist”按正确顺序排列的代码。我只是不知道如何实际让这些部分也更改为该顺序。

现在我的输出文件看起来像:

[DATA]
datalist = ALL, h, cc

[DATA.dict]

[DATA.dict.ALL]
type = Default
from = 748.0
to = 4000.0
line = 0

[DATA.dict.cc]
type = Energy
from = 3213.9954023
to = 3258.85057471
line = 2

[DATA.dict.h]
type = Energy
from = 1127.11016043
to = 1210.58395722
line = 1

我希望它看起来像这样:

[DATA]
datalist = ALL, h, cc

[DATA.dict]

[DATA.dict.ALL]
type = Default
from = 748.0
to = 4000.0
line = 0

[DATA.dict.h]
type = Energy
from = 1127.11016043
to = 1210.58395722
line = 1

[DATA.dict.cc]
type = Energy
from = 3213.9954023
to = 3258.85057471
line = 2

我正在尝试使用此代码,但它也不适用于我。

 config._sections = collections.OrderedDict(sorted(config._sections.items(), key=lambda x: getattr(x, 'from') ))

谢谢!

【问题讨论】:

    标签: python ini


    【解决方案1】:

    ConfigParser 在内部使用OrderedDict,因此您需要按照您需要的顺序重新填充解析器,如下所示:

    from configparser import ConfigParser
    from io import StringIO
    
    ini_file = StringIO('''
    [x]
    hello = 123
    
    [a]
    from = 5.0
    
    [b]
    from = 3.0
    ''')
    
    parser = ConfigParser()
    parser.read_file(ini_file)
    
    
    parser2 = ConfigParser()
    sortable_sections = [s for s in parser if 'from' in parser[s]]
    other_sections = [s for s in parser if 'from' not in parser[s]]
    
    for s in other_sections:
        parser2[s] = parser[s]
    
    for s in sorted(sortable_sections, key=lambda s: parser[s].getfloat('from')):
        parser2[s] = parser[s]
    
    f = StringIO()
    parser2.write(f)
    f.seek(0)
    print(f.read())
    

    输出:

    [x]
    hello = 123
    
    [b]
    from = 3.0
    
    [a]
    from = 5.0
    

    【讨论】:

    • 谢谢!我将如何读取我的 INI 文件?现在我有: configFilePath = datafile.ini parser.read(configFilePath)
    • 它只是为我输出一个空白文件。
    猜你喜欢
    • 1970-01-01
    • 2012-10-11
    • 2015-03-13
    • 2016-09-12
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多