-2

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)
rdev
  • 3
  • 1
  • 1
    How exactly does not "not work"? – chepner Jun 01 '21 at 20:21
  • Note that `input` always returns a string, so your call to `format` isn't really doing anything. You could equivalently write `config['keys']['personal'] = key_name`. – chepner Jun 01 '21 at 20:22
  • @chepner Thank you so much, I didn't realize I could just write the variable like that. – rdev Jun 02 '21 at 05:09

1 Answers1

-1

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'] = {}
config['keys']['personal'] = key_name
with open("./data/settings.ini", "w") as configfile:
    config.write(configfile)
chepner
  • 497,756
  • 71
  • 530
  • 681