简体   繁体   中英

python configparser writes configuration file to one line

I have a configuration file that I would like to change settings to from a python script. Here is my skeleton code:

config = ConfigParser()        
config.read('settings.conf')
config.set("SCRIPT", "SOMEFIELD", "%s"%SOMEVALUE)
config.write(open("settings.conf","wb"))

This works fine, however it writes everything to one line. I might be being a bit picky, but would like to have new lines after each configurations field and section so that the file is human readable.

You are telling python to write a binary file ("b" char on 2nd arg of your open() call).

Use

config.write(open("settings.conf","w"))

Or better:

with open("settings.conf","w") as settings_file:
    config.write(settings_file)

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