我想根据节中的一个键中的数值对.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”值。我也有代码把'数据表'在正确的顺序。我只是不知道怎样才能让这些部分也改变到那个顺序。你知道吗
现在,我的输出文件如下所示:
[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') ))
谢谢你!你知道吗
ConfigParser
在内部使用OrderedDict
,因此您需要按照需要的顺序重新填充解析器,如下所示:输出:
相关问题 更多 >
编程相关推荐