如何编写无节的ini文件? [英] How to write ini-files without sections?
问题描述
我需要以以下格式创建文件:
I need to create a file in the following format:
option1 = 99
option2 = 34
do_it = True
...
当我使用 ConfigParser
时,我必须将所有数据放入带有人工名称的节中,然后它创建一个以 [SECTION]
开头的文件.
When I use ConfigParser
, I have to put all my data into a section with an artificial name, and then it creates a file which starts with [SECTION]
.
import ConfigParser
ini_writer = ConfigParser.ConfigParser()
ini_writer.add_section('SECTION')
ini_writer.set('SECTION', 'option1', 99)
ini_writer.set('SECTION', 'option2', 34)
ini_writer.set('SECTION', 'do_it', True)
with open('my.ini', 'w') as f:
ini_writer.write(f)
如何更改它,使其输出不带虚拟节头的文件?我想使用Python 2.7来做到这一点,但是Python 3解决方案也有帮助(想法是我可以将其移植到Python 2.7).
How can I change it so it outputs the file without the dummy section header? I would like to do it using Python 2.7, but a Python 3 solution would help too (the idea is that I could port it to Python 2.7).
此相关问题显示了如何通过对代码的细微调整来读取此类文件.
This related question shows how to read such files using minor tweaks to the code.
推荐答案
[NB:以下内容适用于Python 3;您需要进行一些小的更改才能使其在Python 2下运行.]
[NB: the following is written for Python 3; you would need to make a couple of minor changes to make it run under Python 2.]
也许像这样;在这里,我向内存中的 io.StringIO
对象写入内容,然后将除第一行以外的所有内容都写到目标文件中.
Maybe something like this; here, I write to an io.StringIO
object in memory, then take everything but the first line and write that out to the target file.
import configparser
import io
buf = io.StringIO()
ini_writer = configparser.ConfigParser()
ini_writer.set('DEFAULT', 'option1', '99')
ini_writer.set('DEFAULT', 'option2', '34')
ini_writer.set('DEFAULT', 'do_it', 'True')
ini_writer.write(buf)
buf.seek(0)
next(buf)
with open('my.ini', 'w') as fd:
fd.write(buf.read())
通过使用节名称 DEFAULT
,我们避免了必须先创建新节的情况.
By using the section name DEFAULT
we avoid having to create a new section first.
结果是:
$ cat my.ini
option1 = 99
option2 = 34
do_it = True
这篇关于如何编写无节的ini文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!