如何使用 python 的 configparser 编写没有节的文件
How to use python's configparser to write a file without sections
我需要使用 python 修改配置文件。该文件的格式类似于
property_one = 0
property_two = 5
即没有任何部分名称。
Python 的 configparser 模块不支持无节文件,但我可以使用这里的技巧轻松加载它们:
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)
它可以工作,但有点难看,并且需要在内存中创建文件的第二个副本。有没有更好或更简洁的方法来实现这一目标?
偶然发现了一种不那么丑陋的方法:
text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
config_file.write(text)
我需要使用 python 修改配置文件。该文件的格式类似于
property_one = 0
property_two = 5
即没有任何部分名称。
Python 的 configparser 模块不支持无节文件,但我可以使用这里的技巧轻松加载它们:
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)
它可以工作,但有点难看,并且需要在内存中创建文件的第二个副本。有没有更好或更简洁的方法来实现这一目标?
偶然发现了一种不那么丑陋的方法:
text = '\n'.join(['='.join(item) for item in parser.items('top')])
with open('foo.conf', 'w') as config_file:
config_file.write(text)