Reputation: 29
Code
import pandas as pd
import csv
my_dict = { 'Customer' : [],
'Product' : []
}
x = input("Customer:")
y = input("Product:")
my_dict['Customer'].append(x)
my_dict['Product'].append(y)
df = pd.DataFrame(my_dict)
df.to_csv('data.csv', encoding='utf-8', index= True)
Output
,Customer,Product
0,Customer 1,Product 1
Question
How can I append new row If I run the script again and input new values?
Example
If I run the script again and my input would be Customer 2
& Product 2
and add new index
too. I want the output to look like this in csv file:
,Customer,Product
0,Customer 1,Product 1
1, Customer 2, Product 2
But at the moment, it is just overwriting it.
Upvotes: 0
Views: 424
Reputation: 364
You want to append the data to the existing data so try to read in the file and append the data:
import pandas as pd
import csv
try: #tries to read in existing data.csv file
df = pd.read_csv('data.csv', encoding='utf-8', index_col = 0)
except FileNotFoundError: #if no file exists yet, create an empty dataframe
df = pd.DataFrame()
my_dict = { 'Customer' : [],
'Product' : []
}
x = input("Customer:")
y = input("Product:")
my_dict['Customer'].append(x)
my_dict['Product'].append(y)
df = df.append(pd.DataFrame(my_dict))
df.to_csv('data.csv', encoding='utf-8', index= True)
Upvotes: 2