【问题标题】:How to use python's configparser to write a file without sections如何使用 python 的 configparser 编写没有节的文件
【发布时间】:2019-06-12 16:31:19
【问题描述】:

我需要使用 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】:

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

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

【讨论】:

    猜你喜欢
    • 2011-02-22
    • 2021-05-14
    • 2015-08-17
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多