比如我想生成一个文档为:
[DEFAULT]serveraliveinterval = 45compression = yescompressionlevel = 9forwardx11 = yes [bitbucket.org]user = hg [topsecret.server.com]host port = 50022forwardx11 = no
可以利用configparser来生成:
import configparser config = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘, ‘Compression‘: ‘yes‘, ‘CompressionLevel‘: ‘9‘} config[‘bitbucket.org‘] = {}config[‘bitbucket.org‘][‘User‘] = ‘hg‘config[‘topsecret.server.com‘] = {}topsecret = config[‘topsecret.server.com‘]topsecret[‘Host Port‘] = ‘50022‘ # mutates the parsertopsecret[‘ForwardX11‘] = ‘no‘ # same hereconfig[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘with open(‘example.ini‘, ‘w‘) as configfile: config.write(configfile)
时间: 2024-11-01 16:50:44