【发布时间】: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') ))
谢谢!
【问题讨论】: