如何使用python的configparser编写无节的文件

问题描述 投票:1回答:1

我需要使用python修改配置文件。该文件的格式类似于

property_one = 0
property_two = 5

即没有任何部分名称。

Python的configparser模块不支持无节文件,但是无论如何我都可以使用它来轻松加载它们,方法如下:https://stackoverflow.com/a/26859985/11637934

parser = ConfigParser()
with open("foo.conf") as lines:
    lines = chain(("[top]",), lines)  # This line does the trick.
    parser.read_file(lines)

问题是,我找不到一种干净的方法来将解析器写回到没有节头的文件中。我目前最好的解决方案是将解析器写入StringIO缓冲区,跳过第一行,然后将其写入文件:

with open('foo.conf', 'w') as config_file, io.StringIO() as buffer:
    parser.write(buffer)
    buffer.seek(0)
    buffer.readline()
    shutil.copyfileobj(buffer, config_file)

可以,但是有点丑陋,需要在内存中创建文件的第二个副本。是否有更好或更简洁的方法来实现这一目标?

python-3.x configparser
1个回答
0
投票

偶然发现了一个不太丑陋的方法:

text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
    config_file.write(text)
© www.soinside.com 2019 - 2024. All rights reserved.