如何用Python更改INI文件中节的顺序?

2024-04-26 13:07:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据节中的一个键中的数值对.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') ))

谢谢你!你知道吗


Tags: 文件to代码fromconfigdefaultdata顺序
1条回答
网友
1楼 · 发布于 2024-04-26 13:07:36

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

相关问题 更多 >