Code to read CSV file & print list of dates per user

91 Views Asked by At

I have a csv dataset containing 4 columns. First name | Last name | Date of Absence | Email

I want to read this file and mass email each employee with the list of dates they were absent on.

I initially started just trying to loop, save and print out this before going to the email part. What I have so far:

 import csv

    first1 = []
    last1 = []
    date1 = []

    with open("file.csv") as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        next(readCSV)  # Skip header row

        first2 = []
        last2 = []
        email1 = []

        first = row[0]
        last = row[1]
        date = row[2]
        email = row[3]

        xfirst = row[0]
        xlast = row[1]

#saves data in array below
        first1.append(first)
        last1.append(last)
        date1.append(date)
        email1.append(email)

        first2.append(xfirst)
        last2.append(xlast)
 #start to print name and body of email   
        print("Dear "+ str(first1) +" "+ str(last1) +",")
        print(" ")
        print("You have been absent for the following dates:")

# check if the previous first/last name is similar to next row first/last name 
# if yes go in loop to save the dates in a list to print them in the rest of them email

        while first1 == first2 and last1 == last2:
            date = row[2]
            date1.append(date)

            del first2[:]
            del last2[:]
    #this next thing doesnt work
            next(readCSV)

            xfirst = row[0]
            xlast = row[1]
            first2.append(xfirst)
            last2.append(xlast)


        for i in date1:
            print(" ")
            print((date1))
            print(" ")

# when done delete the saved name and replace with the next set of names and check
        del first1[:]
        del last1[:]
        del date1[:]            
        del email1[:]

Any help is appreciated!

Thank you!

2

There are 2 best solutions below

1
On

try use pandas to read the csv :

df = pd.read_csv(file)
dg= df.groupby([u'First name ',u' Last name '])[ u' Email',u' Date of Absence '].agg(lambda x:','.join(x))

now you have the first and last name grouped with date of absence and mail

1
On

You can do something like this, taking advantage of dict key.

from collections import defaultdict
import csv

infos = defaultdict[list]
with open("file.csv") as csvfile: 
    readCSV = csv.reader(csvfile, delimiter=',')
    next(readCSV)
    for first, last, date, email in readCSV:
        infos[(first, last, email)].append(date)

#email
for (first, last, email), dates in infos.items():
    print(f" Dear {last})
    print("You have been absent those date :") 
    for date in dates:
        print(f"- {date}")