Random String Generator to CSV

  • Share this:

Code introduction


This code generates random strings of a specified length and writes them to a CSV file. Then it reads the strings from the CSV file and prints them.


Technology Stack : csv, random, string, time

Code Type : Function

Code Difficulty : Intermediate


                
                    
import csv
import random
import string
import time

def generate_random_string(length=10):
    return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))

def write_strings_to_csv(strings, filename='random_strings.csv'):
    with open(filename, mode='w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Random String'])
        for s in strings:
            writer.writerow([s])

def read_strings_from_csv(filename='random_strings.csv'):
    with open(filename, mode='r') as file:
        reader = csv.reader(file)
        next(reader)  # Skip the header
        return [row[0] for row in reader]

def main():
    random_strings = [generate_random_string() for _ in range(100)]
    write_strings_to_csv(random_strings)
    read_strings = read_strings_from_csv()
    print(read_strings)

if __name__ == '__main__':
    start_time = time.time()
    main()
    end_time = time.time()
    print(f"Execution time: {end_time - start_time} seconds")