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

问题描述 投票:0回答:2

我有一个包含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[:]

感谢您的任何帮助!

谢谢!

python csv python-idle email-templates mass-emails
2个回答
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}") 

0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.