首页 > 解决方案 > 如何使用 python 的 configparser 编写没有节的文件

问题描述

我需要使用 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.xconfigparser

解决方案


偶然发现了一种不那么丑陋的方法:

text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
    config_file.write(text)

推荐阅读