Mini Project: Config Manager
Exit
Mini Project: Config Manager
Build a config tool that reads, updates, and saves JSON settings
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
What you will build
A config manager with three functions: load settings from a JSON file, update a value, and save the changes back to disk.
Example output
Current theme: light
Updated theme: dark
Updated max_retries: 5Design
| Function | Purpose |
|---|---|
load_config(filename) | Read and return a JSON config file as a dict |
update_config(config, key, value) | Set config[key] to value |
save_config(config, filename) | Write the config dict back to the JSON file |
Instructions
Build the config manager.
- Import
json. - Define a function named
load_configthat takesfilename. Inside, openfilenamein read mode and returnjson.load(file). - Define a function named
update_configthat takesconfig,key, andvalue. Inside, assignvaluetoconfig[key]. - Define a function named
save_configthat takesconfigandfilename. Inside, openfilenamein write mode and calljson.dump(config, file, indent=2). - Assign
load_config("settings.json")toconfig. Callprint(f"Current theme: {config['theme']}"). - Call
update_config(config, "theme", "dark"). Callupdate_config(config, "max_retries", 5). Callsave_config(config, "settings.json"). - Call
print(f"Updated theme: {config['theme']}"). Callprint(f"Updated max_retries: {config['max_retries']}").
# settings.json contains:
# {"theme": "light", "language": "en", "notifications": true, "max_retries": 3}
# Step 1: Import json
# Step 2: Define load_config(filename)
# Step 3: Define update_config(config, key, value)
# Step 4: Define save_config(config, filename)
# Step 5: Load settings.json and print the current theme
# Step 6: Update theme to "dark", max_retries to 5, and save
# Step 7: Print the updated values
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding