[英]ConfigObj change key=value to key = value which I don't want to
I have conf file with content:我有一个包含内容的 conf 文件:
key1=value1
key2=value2
font="\"Font\""
and it's used like values in bash script.它就像 bash 脚本中的值一样使用。
When I change some value with cgi+python3 and ConfigObj 4.7.0:当我使用 cgi+python3 和 ConfigObj 4.7.0 更改某些值时:
def set_conf_values(filename, param, value):
config = ConfigObj(filename)
config['%s' % param] = value
config.write()
the conf file is rewriten and the format is new: conf 文件被重写并且格式是新的:
key1 = value1
key2 = value2
font = `\"Font\"`
Event for values which is untouched.未触及的值的事件。 That's break my Bash script it takes keys as commands...
这打破了我的 Bash 脚本,它将键作为命令......
I hope there is option to avoid that but can't find such thing in docs.我希望有避免这种情况的选择,但在文档中找不到这样的东西。
There does not seem to be any meaningful way to control the output of ConfigObj.似乎没有任何有意义的方法来控制 ConfigObj 的输出。 ConfigParser, though, has a
space_around_delimiters=False
keyword argument that you can pass to write.但是,
space_around_delimiters=False
有一个space_around_delimiters=False
关键字参数,您可以将其传递给 write。
config.conf:配置文件:
[section1]
key1=value1
key2=value2
font="\"Font\""
code:代码:
import configparser
from validate import Validator
def set_conf_values(filename, section, param, value):
config = configparser.ConfigParser()
config.read(filename)
print({section: dict(config[section]) for section in config.sections()})
config[section]['%s' % param] = value
with open('config2.conf', 'w') as fid:
config.write(fid, space_around_delimiters=False)
filename = 'config.conf'
set_conf_values(filename, 'section1', 'key2','value2_modified')
config2.conf (output): config2.conf(输出):
[section1]
key1=value1
key2=value2_modified
font="\"Font\""
The dreadful thing about ConfigParser is that it REALLY wants section names.关于 ConfigParser 的可怕之处在于它真的想要部分名称。 There are elaborate workarounds for this, but this code will get you started.
对此有详细的解决方法,但此代码将帮助您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.