[英]configparser - create file with key and no value
我必须创建一个类似于此的 ini 文件:
[rke2_servers]
host0
host1
host2
[rke2_agents]
host4
host5
host6
[rke2_cluster:children]
rke2_servers
rke2_agents
我尝试使用以下代码创建文件:
import configparser
def initfile(rke2s, rke2a, filepath):
config = configparser.ConfigParser(allow_no_value=True)
config['rke2_servers'] = {rke2s: ''}
config['rke2_agents'] = {rke2a: ''}
config['rke2_cluster:children'] = {'rke2_servers':'', 'rke2_agents':''}
with open('example.ini', 'w') as configfile:
config.write(configfile)
但结果是这样的:
[rke2_servers]
host0 =
[rke2_agents]
host1 =
[rke2_cluster:children]
rke2_servers =
rke2_agents =
问题是它在每个键后保留“=”
作为一种解决方案,我总是可以在创建后清理文件并删除任何尾随 =,但应该有一种方法可以在 configparser 中保留一个空键,但没有关于它的文档。
尝试使用None
而不是空字符串:
def initfile(rke2s, rke2a, filepath):
config = configparser.ConfigParser(allow_no_value=True)
config['rke2_servers'] = {rke2s: None}
config['rke2_agents'] = {rke2a: None}
config['rke2_cluster:children'] = {'rke2_servers': None, 'rke2_agents': None}
with open('example.ini', 'w') as configfile:
config.write(configfile)
仅供参考,ConfigParser 被记录为提供类似于Microsoft Windows INI 文件中的结构的结构。 (强调我的)所以即使 Windows 需要 INI 文件中的值,也可以在 Python 的配置文件中有空值。
事实上,还有一些您通常不会在 Windows 中找到的其他示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.