Python Forum

Full Version: filtering csv file problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i am trying to write a function to send emails for reminders if todays date matches the dates saved on a csv file. i first go through the csv file, i add the correct reminders and create a list, i then fill that list with reminders that match todays date. i then go through that list in order to loop through all of the results and pop up a messagebox to confirm sending the email. the problem is i get every entry that matches twice in a row and i cant find the issue with my code. my code follows


def emails_func():
    """Check reminders for the current date and prompt to send notifications."""
    search_results=[]
    todays_date=datetime.now().strftime("%d-%m-%Y")
    send_dates=[]
    try:
        df=pd.read_csv("data.csv")
    except FileNotFoundError:
        messagebox.showerror(title="OOOOOOOOps",message="You have no saved data.\nPlease save some info and search again!!\n")
    else:
        saved_data=df.to_dict("records")
        for ent in saved_data:
            if ent["recurring"]:
                send_dates.extend(ent["send date"].split(","))
        for ent in saved_data:
            for date in send_dates:
                current_date = "".join(letter for letter in date if letter.isalnum).replace("'", "").replace("[","").replace("]", "")
                if todays_date == current_date:
                    print("Match found")
                    search_results.append({"name": ent["name"],"send date": current_date,"email address":ent["email address"],"phone number": ent["phone number"],"description":ent["description"]})
        if len(search_results)>0:

            for date in search_results:
                full_name=date["name"].split(" ")
                f_name=full_name[0].replace("'","").replace("]","").replace('[','').replace(']','')
                l_name=full_name[1].replace("[","").replace("'","").replace('[','').replace(']','')
                final_phone_number="+44"+str(date["phone number"]).replace("'","").replace("]","")[2:]
                final_description=date["description"].replace("[","").replace("'","").replace("]","")
                to_email_address=date["email address"].replace("[","").replace("'","").replace("'","").replace("]","")
                if messagebox.askyesno(
                                 title="Found Reminders",
                                message=f"On {get_due_date()}, {f_name} {l_name} will have to {final_description} "
                                         f"They will be reminded on the {date['send date']}\n"
                                         f"by contacting them on {to_email_address}\n"
                                          f"Do you want to send this email now?\n "):
                    connection=smtplib.SMTP("smtp.gmail.com")
                    connection.starttls()
                    connection.login(user=my_email,password=password)
                    message_body=f"Hello {l_name}, {f_name} this is a friendly reminder that on {get_due_date()} you will have to {final_description}"
                    connection.sendmail(from_addr=my_email,to_addrs=to_email_address,msg=message_body)

        else:

            messagebox.showinfo(title="Looking for reminders", message="I have completed looking for reminders whose date matches todays date!\nI have come up with nothing!!\nSee you again tomorrow!!")
please help me if you can.. thanks for your time
Your data is all messed up because your csv file is all messed up. When you find yourself writing something that looks like this:
                f_name=full_name[0].replace("'","").replace("]","").replace('[','').replace(']','')
                l_name=full_name[1].replace("[","").replace("'","").replace('[','').replace(']','')
You need step back and look at your design. There are problems that make you write this ugly code. Those are the problems you need to fix. I don't think you fixed your problem with saving data to the csv file. CSV is a poor choice for this kind of data where not all rows are the same. In your code some events have multiple send dates and some only have one. That is hard to save in a CSV file, but no problem at all in a json file.

I really think you should think about json. On your other thread I added a post about how you would write your code if you were using json to save the data. Based on that post, this is how I would rewrite your cde for this post.
from datetime import datetime
from tkinter import messagebox
import json
import smtplib


date_format = "%d/%m/%Y"


def search_events(date):
    """Return events that have date in the date send list."""
    try:
        with open("events.json", "r") as file:
            events = json.load(file)
        return [event for event in events if date in event["date"]["send"]]
    except IOError:
        messagebox.showerror(title="OOOOOOOOps",message="You have no saved data.\nPlease save some info and search again!!\n")
    return []


def send_reminders():
    """Send today's reminders."""
    connection = smtplib.SMTP("smtp.gmail.com")
    connection.starttls()
    connection.login(user=my_email, password=password)

    for event in search_events(datetime.now().strftime(date_format)):
        if messagebox.askyesno(
            title="Found Reminders",
            message=(
                f"On {event['date']['due']}, {event['name']} will have to {event['description']} "
                f"They will be reminded on the {event['date']['send']}\n"
                f"by contacting them on {event['email']}\n"
                "Do you want to send this email now?\n "
            )
        ):
            message_body=f"Hello {event['name']} this is a friendly reminder that on {event['date']['due']} you will have to {event['description']}"
            connection.sendmail(from_addr=my_email, to_addrs=event['email'], msg=message_body)

    connection.quit()
Using a json, an event with multiple send dates has a list with multiple send dates, and events with a single send date has a list with one send date. This makes it really easy to find if today is found in the send dates for an event. Notice that I don't have to clean up the data at all. No removing brackets and commas.