function save_results_v1
Saves a list of dictionary results to both CSV and JSON file formats with UTF-8 encoding.
/tf/active/vicechatdev/mailsearch/enhanced_document_comparison.py
365 - 376
simple
Purpose
This function provides a convenient way to persist structured data (list of dictionaries) to disk in two common formats: CSV for tabular data analysis and JSON for structured data interchange. It handles file writing with proper encoding, creates headers from dictionary keys for CSV, and formats JSON with indentation for readability. Useful for exporting processing results, data analysis outputs, or any structured data that needs to be saved in multiple formats simultaneously.
Source Code
def save_results(results: List[Dict], csv_file: str, json_file: str):
"""Save results to CSV and JSON"""
print(f"\nā Saving CSV results to: {csv_file}")
with open(csv_file, 'w', newline='', encoding='utf-8') as f:
if results:
writer = csv.DictWriter(f, fieldnames=results[0].keys())
writer.writeheader()
writer.writerows(results)
print(f"ā Saving JSON results to: {json_file}")
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
results |
List[Dict] | - | positional_or_keyword |
csv_file |
str | - | positional_or_keyword |
json_file |
str | - | positional_or_keyword |
Parameter Details
results: A list of dictionaries containing the data to be saved. Each dictionary should have the same keys, which will become column headers in the CSV file. Can be an empty list, in which case empty files will be created. All values should be JSON-serializable.
csv_file: String path (absolute or relative) to the output CSV file. The file will be created or overwritten if it exists. Should include the .csv extension. Parent directories must exist.
json_file: String path (absolute or relative) to the output JSON file. The file will be created or overwritten if it exists. Should include the .json extension. Parent directories must exist.
Return Value
This function returns None. It performs side effects by writing to the filesystem and printing status messages to stdout. Success is indicated by the creation/update of the specified files.
Dependencies
csvjson
Required Imports
import csv
import json
from typing import List, Dict
Usage Example
import csv
import json
from typing import List, Dict
def save_results(results: List[Dict], csv_file: str, json_file: str):
"""Save results to CSV and JSON"""
print(f"\nā Saving CSV results to: {csv_file}")
with open(csv_file, 'w', newline='', encoding='utf-8') as f:
if results:
writer = csv.DictWriter(f, fieldnames=results[0].keys())
writer.writeheader()
writer.writerows(results)
print(f"ā Saving JSON results to: {json_file}")
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(results, f, indent=2, ensure_ascii=False)
# Example usage
data = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "San Francisco"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
]
save_results(data, "output.csv", "output.json")
# This will create:
# - output.csv with headers and 3 rows
# - output.json with formatted JSON array
Best Practices
- Ensure all dictionaries in the results list have the same keys to avoid CSV formatting issues
- Verify that parent directories exist before calling this function, as it does not create them
- Handle potential IOError or PermissionError exceptions when calling this function in production code
- If results list is empty, the CSV file will be created but will be empty (no headers)
- All dictionary values must be JSON-serializable (no custom objects without __dict__ or serialization methods)
- The function uses 'w' mode which will overwrite existing files without warning
- UTF-8 encoding with ensure_ascii=False preserves non-ASCII characters in JSON output
- Consider validating that all dictionaries have consistent keys before calling this function
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_results 81.8% similar
-
function export_results 66.0% similar
-
function save_document_to_file 57.9% similar
-
function generate_failure_report 55.7% similar
-
function save_session_to_disk_v1 53.6% similar