gpt4 book ai didi

python - 将当前日期与 CSV 文件匹配并打印匹配项

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:01 25 4
gpt4 key购买 nike

嗨,我正在写一个 python 脚本来发送生日邮件之类的东西。但我被困在中间。我有一个包含姓名和生日的 csv 文件,并且已经编写了代码来获取当前日期,

#Import Date
import datetime
CurrentDate = datetime.datetime.now().date()
CurrentDate = CurrentDate.strftime("%d-%B-%Y")
print(CurrentDate)

我的 csv 文件是

user1,13-September-2016
user2,19-October-2016
user3,13-September-2016
user4,25-August-2016

所以我想要的是将当前日期与此 csv 的第二列匹配,并获取相应列的一个值并将它们导出为字符串,就像我从 datetime 获取 CurrentDate 一样。如果有多个用户在相应日期过生日,则应在他们的姓名之间打印“和”。我希望我问这个问题没有犯任何错误:)

最佳答案

只需将它们分组在一个列表中并输出您想要的任何内容:

import csv
from datetime import datetime
today = datetime.now().date().strftime("%d-%B-%Y")

with open("b.csv") as f:
has_birthday = [user for user, birthday in csv.reader(f) if birthday == today]
print(has_birthday)

输出:

['user1', 'user3']

您可以根据 has_birthday 的长度添加自定义消息:

has_birthday = [user for user, birthday in csv.reader(f) if birthday == today]
frm = "{} have their birthdays today." if len(has_birthday) > 1 else "{} has their birthday today."
print(frm.format(" and ".join(has_birthday or ["Nobody"])))

因此,对于一个匹配的生日:

userx has their birthday today.

对于多个:

userx and Usery have their birthdays today.

对于没有用户:

Nobody has their birthday today.

关于python - 将当前日期与 CSV 文件匹配并打印匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39468735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com