Spaces:
Running
Running
File size: 1,999 Bytes
6c8a2d5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
import json
import os
class Config:
def __init__(self, file_path="config.json"):
self.file_path = file_path
self.data = {}
self.load()
def load(self):
"""Loads the configuration data from the JSON file."""
try:
with open(self.file_path, "r", encoding="utf-8") as f:
self.data = json.load(f)
except FileNotFoundError:
print(f"Config file not found at {self.file_path}. Creating a new one.")
self.data = {} # Start with an empty config
self.save()
except json.JSONDecodeError:
print(
f"Error: Invalid JSON format in config file at {self.file_path}. The file will be reset."
)
self.data = {}
self.save()
def save(self):
"""Saves the configuration data to the JSON file."""
with open(self.file_path, "w", encoding="utf-8") as f:
json.dump(self.data, f, indent=4, ensure_ascii=False)
def get(self, key, default=None):
"""Gets a configuration value by key.
Args:
key (str): The key to look up.
default: The default value to return if the key is not found.
Returns:
The configuration value or the default.
"""
return self.data.get(key, default)
def set(self, key, value):
"""Sets a configuration value.
Args:
key (str): The key to set.
value: The value to set.
"""
self.data[key] = value
self.save()
def update(self, new_data):
"""Updates the config data with a new dict
Args:
new_data: The data to update
"""
self.data.update(new_data)
self.save()
def delete(self, key):
"""Deletes a key from the config
Args:
key (str): the key to delete
"""
if key in self.data:
del self.data[key]
self.save()
|