簡體   English   中英

configparser - 創建帶有鍵但沒有值的文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM