CSV to JSON Conversion with Random String Generation

  • Share this:

Code introduction


This function first generates a random string using the random and string libraries, then writes it to a CSV file. Then, it uses the csv and json libraries to convert the CSV file to JSON format and save it to a file. Finally, the original CSV file is deleted.


Technology Stack : random, string, csv, json, os

Code Type : Function

Code Difficulty :


                
                    
import csv
import json
import math
import os
import random
import re
import string
import sys
import time

def generate_random_string(length):
    letters = string.ascii_letters
    return ''.join(random.choice(letters) for i in range(length))

def process_csv_to_json(csv_file_path, json_file_path):
    with open(csv_file_path, mode='r', encoding='utf-8') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        data = [row for row in csv_reader]
    
    with open(json_file_path, mode='w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)

def xxx(arg1, arg2):
    # This function generates a random string of a specified length and saves a CSV file to JSON format
    random_string = generate_random_string(arg1)
    csv_content = f'Name,{random_string}\n'
    csv_file_path = 'output.csv'
    json_file_path = 'output.json'
    
    # Write the CSV content to a file
    with open(csv_file_path, mode='w', encoding='utf-8') as csv_file:
        csv_file.write(csv_content)
    
    # Process the CSV file to JSON
    process_csv_to_json(csv_file_path, json_file_path)
    
    # Remove the CSV file after processing
    os.remove(csv_file_path)