Search code examples
pythonpython-3.xconfigparser

ConfigParser is successfully setting new values, but doesn't show up in ini Python 3


I'm having some trouble getting config parser module to work. I'm currently in the process of creating a file backup program, but whenever I set the values they don't show up in the .ini file. config.get confirms that it was set correctly, but document_backup.ini is blank.

config = configparser.ConfigParser()
config.read('document_backup.ini')
config.set('FTP_Login','Host',input("FTP Host: "))
config.set('FTP_Login','UserName',input("FTP UserName: "))
config.set('FTP_Login','Password',input("FTP Password: "))
config.read('') #To close the file, I think

Solution

  • Modifying the in-memory configuration does not affect the file it was originally read from. You need to write the new configuration back to disk.

    config = configparser.ConfigParser()
    config.read('document_backup.ini')
    config.set('FTP_Login','Host',input("FTP Host: "))
    config.set('FTP_Login','UserName',input("FTP UserName: "))
    config.set('FTP_Login','Password',input("FTP Password: "))
    with open("document_backup.ini.new", "w") as fh:
        config.write(fh)
    os.rename("document_backup.ini", "document_backup.ini~")
    os.rename("document_backup.ini.new", "document_backup.ini")
    

    Note that the configparser module doesn't provide any way to edit an existing configuration file. The new file will produce an equivalent configuration, but may not have the same form as the original.