简体   繁体   中英

Using normal python variables and writing them into configparser

Hello I'm just starting out with my first python projects. The python variable "key_name" is asked from the user. This variable should then be written into the configparser file under the section [keys] -> personal. Basically where the "{}" are. And I can't quite figure it out.

I tried this but it doesn't work:

key_name = input("\nPublic key name: ")
    config = configparser.ConfigParser()
    config['keys']['personal'] = '{}'.format(key_name)
    with open("./data/settings.ini", "w") as configfile:
        config.write(configfile)

You have to initialize config['keys'] before you can add variables to that section. (You will also need to ensure that ./data exists before calling open ; it can create the file settings.ini in that directory, but it will not create the directory for you.)

key_name = input("\nPublic key name: ")
config = configparser.ConfigParser()

config['keys']['personal'] = key_name
with open("./data/settings.ini", "w") as configfile:
    config.write(configfile)

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