简体   繁体   中英

configparser - create file with key and no value

I have to create an ini file similar to this:

[rke2_servers]
host0 
host1 
host2 

[rke2_agents]
host4
host5
host6

[rke2_cluster:children]
rke2_servers
rke2_agents

I tried to create the file using this code:

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)

but the result is this:

[rke2_servers]
host0 = 

[rke2_agents]
host1 = 

[rke2_cluster:children]
rke2_servers = 
rke2_agents = 

The problem is that it keeps the "=" after every key

As a solution I can always clean the file after creation and remove any trailing =, but there should be a way to keep an empty key in configparser, but there is no documentation about it.

Try using None instead of an empty string:

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)

FYI, ConfigParser is documented as providing a structure similar to what's found in Microsoft Windows INI files. (emphasis mine) So even though Windows requires values in INI files, it's ok to have empty values in config files in Python here.

In fact, there are other examples that you normally wouldn't find in Windows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM