Get Config Value
Description
The get_config_value
function retrieves the value of a configuration file stored as a plain text file in a specified folder. If the config file doesn't exist, it will be created with a default value.
Function Signature:
def get_config_value(config_folder_path: str, name: str, default_value: str = '') -> str | None:
Parameters
- config_folder_path (str): The path to the folder where the configuration file is located or should be created.
- name (str): The name of the config file (without extension).
- default_value (str, optional): The value to write to the file if it doesn’t exist. Defaults to an empty string.
Returns
- str | None: Returns the contents of the config file as a string. Returns
None
if an error occurs during reading.
Example Usage
config_path = get_config_folder_path("MyCoolApp")
api_key = get_config_value(config_path, "api_key", "default_api_key_123")
print(f"API Key: {api_key}")
Behavior
- If the configuration folder doesn’t exist, it is created automatically.
- If the target config file does not exist, it is created with the given default value.
- The contents are read and returned as a trimmed string.
Error Handling
- If the file is not found after the initial write attempt, a warning is printed and
None
is returned. - If an exception occurs while reading the file, an error message is printed and
None
is returned.