我想根据一个节的键之一中的数值对.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') ))
谢谢!
答案 0 :(得分:0)
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