生日自动邮件程序报错:TypeError: 'int' object is not subscriptable
修复TypeError: 'int' object is not subscriptable错误
报错的核心原因:
你用orient="index"将DataFrame转为字典后,data的结构是**{整数索引: 用户信息字典}。直接for d in data遍历的是字典的键**(也就是那些整数索引),不是存储用户信息的字典值,所以执行d['day']时,本质是在对一个整数做下标访问,自然会触发int object is not subscriptable错误。
同时你的代码里还有个笔误:data = bd.to_dict(orient="index")应该是data = bday.to_dict(orient="index")(前面读取csv的变量是bday)。
修正后的完整代码
LETTERS = ["letter_1.txt", "letter_2.txt", "letter_3.txt"] # 修正笔误,并重命名变量避免混淆 bday_df = p.read_csv("birthdays.csv") data = bday_df.to_dict(orient="index") now = d.datetime.now() current_day = now.day current_month = now.month # 遍历字典的values,直接拿到每个用户的信息字典 for user_info in data.values(): bday_day = user_info['day'] bday_month = user_info['month'] if current_day == bday_day and current_month == bday_month: recipient = user_info['email'] letter_choice = r.choice(LETTERS) with open(f"./letter_templates/{letter_choice}", mode="r") as l: orig_letter = l.read() r_letter = orig_letter.replace(PLACEHOLDER, user_info['name']) with s.SMTP("smtp.gmail.com") as connection: connection.starttls() connection.login(user=MY_EMAIL, password=PASSWORD) connection.sendmail( from_addr=MY_EMAIL, to_addrs=recipient, msg=f"subject:Happy Birthday\n\n{r_letter}" )
关键改动点
- 修正循环逻辑:用
data.values()遍历,直接获取每个用户的信息字典,替代原来遍历字典键的方式,这样就能正常用user_info['day']访问字段。 - 修正笔误:把
bd.to_dict改为bday_df.to_dict,保证变量引用正确。 - 变量名优化:将
day/month改为current_day/current_month,循环内的bday改为bday_day,避免和初始的csv数据变量冲突,提升代码可读性。
内容的提问来源于stack exchange,提问作者Mathew Still
相关产品推荐
相关产品推荐

