Python configparser追加

问题描述 投票:-1回答:2

是否可以使用configparser将值附加到配置文件中?

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
message = first run, second run, third run

我想附加如下所示的消息值

message = first run, second run, third run, fourth run.

有可能,有人可以帮忙吗?

python configparser
2个回答
1
投票

有可能,有人可以帮忙吗?

是,只是parse your file,将其他位连接到要修改的条目,然后write it back

ConfigParser除了节和项之外没有其他结构,因此条目只是任意字符串数据。如果您想要更结构化的东西(例如,使条目为数组),则应使用toml之类的东西,那么您可以将[单个项添加到条目中,而不必进行字符串串联。


1
投票
请注意,configparser没有实现文件编辑器;它从文件读取配置,然后将配置写入文件。对配置的任何更改都会在内存中进行,直到再次将整个配置写出。

# Read into memory config = configparser.ConfigParser() with open("config.ini") as f: config.read_file(f) # Update the in-memory configuration config["DEFAULT"]["message"] +=", fourth run" # Write configuration to disk # WARNING: You should write to a temporary file first, # so that you can safely replace config.ini after # the write succeeds. with open("config.ini", "w") as f: config.write(f)

© www.soinside.com 2019 - 2024. All rights reserved.