Jul-01-2024, 10:17 AM
(Jun-30-2024, 03:55 AM)deanhystad Wrote: If you are using pandas, why are you using a CSV writer? Pandas knows how to read and write CSV files. Your save_info function should be:
events_dataframe.to_csv(csv_filename)I think csv files and pandas are poor fits for your problem. I would use a json file and dictionaries, or maybe a dataclass. Pandas does a poor job acting like a list.
import pandas as pd from datetime import datetime import json date_format = "%m/%d/%Y" def add_event(events): events.append({ "name": input("Name: "), "description": input("Description: "), "date": datetime.strptime(input("Date: "), date_format), }) def print_events(events): temp = events.copy() for event in temp: event["date"] = event["date"].strftime(date_format) print(pd.DataFrame(temp)) def load_events(filename): try: with open(filename, "r") as file: events = json.load(file) for event in events: event["date"] = datetime.strptime(event["date"], date_format) return events except IOError: return [] def save_events(filename, events): temp = events.copy() for event in temp: event["date"] = event["date"].strftime(date_format) with open(filename, "w") as file: json.dump(events, file) events = load_events("events.json") while True: choice = input("1: Add event\n2: Print events\n3: Quit\n> ") if choice == '1': add_event(events) elif choice == '2': print_events(events) elif choice == '3': break save_events("events.json", events)
i use both csvwriter and pandas library approaches to practice using both of them. plus with the csvwriter approach i get to just add the headers. and clear all of the data. i chose list of dictionaries (dataframes/csv) because it is easy to get a hold of data by something like the following
from tkinter import messagebox import pandas as pd current_time = datetime.now().strfttime("%d%m%Y") df=pd.read_csv("data.csv") saved_data=df.to_dict("records") for entry in saved_data: if ent["send_date"]==current_time: if messagebox.askyesorno(title="Save information",message=f"On {ent['send_date']} {ent['name']} should be reminded to {ent['task']}\nShould i send this sms?")so for my purposes a csv file is more fitting seeing as with json file i would have a problem with choosing which value to use as the key. if i were to use json i would maybe use the send date as a key and the value as a dictionary that has name,task,phone number and email address key and value pairs. but seeing how there may be multiple tasks to remind about in the same day then the json file approach loses its appeal.
if you can please help me with the subject at hand (writing string instead of list of strings in a csv cell) i would greatly appreciate it.