Utils - File Handlers
smarter.common.utils.file_handlers
Utility functions for the Smarter framework for reading YAML and CSV files.
This module provides helper functions to read YAML and CSV files in a safe and convenient way, returning their contents as Python data structures. It is intended for use throughout the Smarter framework wherever configuration or data files need to be loaded.
Functions
get_readonly_yaml_file(file_path): Reads a YAML file and returns its contents as a dictionary.
get_readonly_csv_file(file_path): Reads a CSV file and returns its contents as a list of dictionaries.
- raises Exceptions may be raised if files do not exist, are unreadable, or contain invalid data.:
Example
from smarter.common.utils import get_readonly_yaml_file, get_readonly_csv_file
config = get_readonly_yaml_file('/path/to/config.yaml')
data = get_readonly_csv_file('/path/to/data.csv')
- smarter.common.utils.file_handlers.get_readonly_csv_file(file_path)[source]
Reads a CSV file from the specified path and returns its contents as a list of dictionaries.
- Parameters:
file_path (str) – The path to the CSV file to be read. This should be a string representing a valid file system path.
- Returns:
A list of dictionaries, where each dictionary represents a row in the CSV file. The keys of each dictionary correspond to the column headers in the CSV.
- Return type:
Note
The file is opened in read-only mode with UTF-8 encoding. The function uses
csv.DictReaderto parse the file, which means the first row must contain the column headers.Warning
If the file does not exist, is not readable, or is not a valid CSV, an exception will be raised. Always validate the file path and ensure the CSV is properly formatted.
Example usage:
from smarter.common.utils import get_readonly_csv_file rows = get_readonly_csv_file('/path/to/data.csv') for row in rows: print(row) # {'column1': 'value1', 'column2': 'value2', ...}
- smarter.common.utils.file_handlers.get_readonly_yaml_file(file_path)[source]
Reads a YAML file from the specified path and returns its contents as a Python dictionary.
- Parameters:
file_path (str) – The path to the YAML file to be read. This should be a string representing a valid file system path.
- Returns:
The contents of the YAML file, parsed into a Python dictionary. If the file is empty or contains no valid YAML,
Nonemay be returned.- Return type:
Note
This function opens the file in read-only mode with UTF-8 encoding and uses
yaml.safe_loadfor parsing. Only standard YAML types are supported.Warning
If the file does not exist, is not readable, or contains invalid YAML, an exception will be raised. Always validate the file path and contents before use.
Example usage:
from smarter.common.utils import get_readonly_yaml_file config = get_readonly_yaml_file('/path/to/config.yaml') print(config) # {'key': 'value', ...}