...
/How to Read, Update and Delete Options
How to Read, Update and Delete Options
We'll cover the following...
Now we’re ready to learn how to read the config file, update its options and even how to delete options. In this case, it’s easier to learn by actually writing some code! Just add the following function to the code that you wrote above.
Press + to interact
import configparserimport osdef createConfig(path):"""Create a config file"""config = configparser.ConfigParser()config.add_section("Settings")config.set("Settings", "font", "Courier")config.set("Settings", "font_size", "10")config.set("Settings", "font_style", "Normal")config.set("Settings", "font_info","You are using %(font)s at %(font_size)s pt")with open(path, "w") as config_file:config.write(config_file)def crudConfig(path):"""Create, read, update, delete config"""if not os.path.exists(path):createConfig(path)config = configparser.ConfigParser()config.read(path)# read some values from the configfont = config.get("Settings", "font")font_size = config.get("Settings", "font_size")# change a value in the configconfig.set("Settings", "font_size", "12")# delete a value from the configconfig.remove_option("Settings", "font_style")# write changes back to the config filewith open(path, "w") as config_file:config.write(config_file)if __name__ == "__main__":path = "settings.ini"crudConfig(path)
This code first checks to see if the path for the config file exists. If it does not, then it uses the createConfig ...