# Write a value to a config file - Python
Data Science for Political and Social Phenomena
Author: Guillaume Redoulès

# Write a value to a config file

You can store variables in an ini file for later executions of the script instead of hardcoding the values in the script. ConfigParser can take a pointer to a file an write values to that file using the ini syntaxe

    config = ConfigParser()
    config.read("file.ini")
    config.set("my_section", "my_param", "my_value")
    with open("file.ini", "w") as f:
        config.write(f)

Here is a function designed to help you update ini files

    def saveParam(pathToFile, section, param, value):
        """
        Save/add value to an ini file
        pathToFile : string, path to the ini file
        section : string, name of the section to write to
        param : string, name of the parameter to write the value to
        value : value to be written to the parameter

        If the file doesn't exist, it will be created
        If the section doesn't exist, it will be created
        """

        config = ConfigParser()

        if not os.path.isfile(pathToFile):
        #create the file if it does not exist
            with open(pathToFile, "w") as f:
                pass
        config.read(pathToFile)
        if not config.has_section(section):
        #create the section if it does not exist
            config.add_section(section)
        config.set(section, param, value)
        with open(pathToFile, "w") as f:
        #write value to the file
            config.write(f)

### Find an error or bug? Have a suggestion?

Everything on this site is avaliable on GitHub. Head on over and submit an issue. You can also message me directly by email.