šŸ” Code Extractor

function save_results_v1

Maturity: 52

Saves a list of dictionary results to both CSV and JSON file formats with UTF-8 encoding.

File:
/tf/active/vicechatdev/mailsearch/enhanced_document_comparison.py
Lines:
365 - 376
Complexity:
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

  • csv
  • json

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function save_results 81.8% similar

    Saves comparison results data to both CSV and JSON file formats with predefined field structure and UTF-8 encoding.

    From: /tf/active/vicechatdev/mailsearch/compare_documents.py
  • function export_results 66.0% similar

    Exports correlation analysis results to multiple CSV files, including overall correlations, grouped correlations, and significant findings.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/5a059cb7-3903-4020-8519-14198d1f39c9/analysis_1.py
  • function save_document_to_file 57.9% similar

    Persists a document object to the filesystem as a JSON file, using the document's ID as the filename.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function generate_failure_report 55.7% similar

    Analyzes processing results from a JSON file, generates a comprehensive failure report with statistics and error categorization, and exports detailed failure information to a CSV file.

    From: /tf/active/vicechatdev/mailsearch/generate_failure_report.py
  • function save_session_to_disk_v1 53.6% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings for storage.

    From: /tf/active/vicechatdev/docchat/blueprint.py
← Back to Browse