Reputation: 43
I've posted about this before using import csv and couldn't figure it out, but now I've decided to step it "up a notch" and use pandas instead. When I try to add data using User Input, I cannot figure out why it won't update. I attempted to look up some solutions online but can't find any. I will add my code and then a photo of what the CSV file looks like and another photo of what the actual program looks like when information is entered into the command line . What I'm trying to accomplish is have a new Name, Location, and Email added at the end of the data(CSV file) and then saved. But nothing happens when it is entered.
import pandas as pd
dataset = pd.read_csv(r'C:\Users\benji\OneDrive\Desktop\My Coding Work\.vscode\.vscode\CSVFiles\emails_demo.csv')
names = list(dataset.Name)
locations = list(dataset.Location)
emails = list(dataset.Email)
def get_email_by_loc(location):
correct_emails = list(dataset.loc[dataset.Location == location].Email)
return correct_emails
def add_data():
global names
global locations
global emails
global dataset
add_name = input('Enter Name: ')
add_location = input('Enter Location: ')
add_email = input('Enter Email: ')
names.append(add_name)
locations.append(add_location)
emails.append(add_email)
while True:
start_search = input('What would you like to search?(Name/Location/Email/Add Data): ')
if start_search == 'Location' or start_search == 'location':
location_search = input('Enter Location: ')
for emails in get_email_by_loc(location_search):
print(emails)
if start_search == 'Add Data' or start_search == 'add data':
add_data()
CSV: https://i.sstatic.net/mMp1R.jpg
Command Line: https://i.sstatic.net/o5WcJ.jpg
Upvotes: 0
Views: 965
Reputation: 271
names = list(dataset.Name)
locations = list(dataset.Location)
emails = list(dataset.Email)
returns list that are not associated with the original dataframe (ie you are appending to arrays that are not even associated with the original dataframe) so when you are going to rewrite to the csv file, you are not appending to the original dataframe. I would recommend fixing the add_data function to append to the end of the dataframe. One quick (but no where close to ideal) version to do so would be
def add_data():
global dataset
add_name = input('Enter Name: ')
add_location = input('Enter Location: ')
add_email = input('Enter Email: ')
dataset.loc[len(dataset)]=[add_name,add_location,add_email ]
If you would like to write to the original csv file, you may use dataset.to_csv(file_path)
This is more ideal, let me know if it works
Upvotes: 1