Python Forum
writing list to csv file problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
writing list to csv file problem
#5
(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.
Reply


Messages In This Thread
RE: writing list to csv file problem - by jacksfrustration - Jul-01-2024, 10:17 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
Bug Writing in a document problem IOHANNES 4 1,240 Oct-26-2022, 08:58 PM
Last Post: IOHANNES
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,630 Sep-27-2022, 01:38 PM
Last Post: buran
  Writing to json file ebolisa 1 1,118 Jul-17-2022, 04:51 PM
Last Post: deanhystad
  Problem with "Number List" problem on HackerRank Pnerd 5 2,303 Apr-12-2022, 12:25 AM
Last Post: Pnerd
  Writing to External File DaveG 9 2,828 Mar-30-2022, 06:25 AM
Last Post: bowlofred
  problem writing dataframe to oracle aliyesami 4 2,823 Sep-25-2021, 11:20 PM
Last Post: SamHobbs
  Writing to file ends incorrectly project_science 4 2,933 Jan-06-2021, 06:39 PM
Last Post: bowlofred
  Writing unit test results into a text file ateestructural 3 5,032 Nov-15-2020, 05:41 PM
Last Post: ateestructural
  Writing to file in a specific folder evapa8f 5 3,675 Nov-13-2020, 10:10 PM
Last Post: deanhystad
  list from a data file problem Marre 3 2,901 Sep-22-2020, 07:55 AM
Last Post: Marre

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020