简体   繁体   中英

ConfigObj change key=value to key = value which I don't want to

I have conf file with content:

key1=value1
key2=value2
font="\"Font\""

and it's used like values in bash script.

When I change some value with cgi+python3 and 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:

key1 = value1
key2 = value2
font = `\"Font\"`

Event for values which is untouched. That's break my Bash script it takes keys as commands...

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. ConfigParser, though, has a space_around_delimiters=False keyword argument that you can pass to 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):

[section1]
key1=value1
key2=value2_modified
font="\"Font\""

The dreadful thing about ConfigParser is that it REALLY wants section names. There are elaborate workarounds for this, but this code will get you started.

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