读取CSV文件并打印每个用户的日期列表的代码

时间:2019-10-20 09:49:28

标签: python csv email-templates mass-emails

我有一个包含4列的csv数据集。 名|姓|缺席日期|电子邮件

我想阅读此文件,并通过电子邮件将其缺席的日期列表发送给每位员工。

在进入电子邮件部分之前,我最初只是尝试循环,保存并打印出来。我到目前为止所拥有的:

 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[:]

感谢您的帮助!

谢谢!

2 个答案:

答案 0 :(得分:1)

尝试使用熊猫读取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))

现在您的名字和姓氏已按缺勤日期和邮件分组

答案 1 :(得分:0)

您可以利用dict键来做类似的事情。

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}")