################################################################################
# - Read a CSV file into a list of dictionaries
# - Write a list of dictionaries into a CSV file
################################################################################
import csv

### Read a CSV file into a list of dictionaries ################################
def readCSV(filename):
    list = []

    try:
        with open(filename) as csvfile:                     #open the file for read
            reader = csv.DictReader(csvfile)                #create a dictionay reader 
            for row in reader:                              #read every row (a row is a dictionary) 
                list.append(row)                            #append to a list
    except Exception as e:
        print(F"Error reading input file - {e}")
 
    return(list)                                            #the list of dictionaries      


### Write a list of dictionaries into a CSV file ###############################
def writeCSV(list, filename):

    if not list: return(False)                                  #if empty list, return 
    
    keys = list[0].keys()                                       #get the keys (col headers) from the first row 

    try:
        with open(filename,"w",newline="") as csvfile:          #open for write. Do not add a newline after each line
            writer = csv.DictWriter(csvfile, fieldnames=keys)   #create a dictionary writer 
            writer.writeheader()                                #write the headers as first line                                               
            for dict in list:                                   #loop thru the list
                writer.writerow(dict)                           #write dictionary (without the headers)
    except Exception as e:
         print(F"Error writing to output file - {e}")
         return(False)
 
    return(True)      
 

### main code (test only) ######################################################

# input_file  = '/users/samsu/desktop/students.csv'
# output_file = '/users/samsu/desktop/students2.csv'

# list  = readCSV(input_file)
# is_ok = writeCSV(list, output_file)