How do I read and write addtional data to existing data in a csv file?
Question:
my csv re-writes new data instead of appending to existing data, so I want to add more data to existing data. And also, how can I skip header when looping through my csv file?
my_file = open("data/food_and_nutrition.csv",'w', encoding='UTF8')
writer = csv.writer(my_file)
Answers:
By using r+ mode, this will allow you to read and append new data to existing data. to skip the header line in your file, do this next(my_file)
The code below should help you through.
with open("data/food_and_nutrition.csv" 'r+', encoding='UTF8', newline='') as my_file:
writer = csv.writer(my_file)
csv_reader = csv.reader(my_file)
# Skip CSV heading
next(csv_reader)
for line in csv_reader:
if new_data not in line:
# To write
writer.writerow(new_data)
my csv re-writes new data instead of appending to existing data, so I want to add more data to existing data. And also, how can I skip header when looping through my csv file?
my_file = open("data/food_and_nutrition.csv",'w', encoding='UTF8')
writer = csv.writer(my_file)
By using r+ mode, this will allow you to read and append new data to existing data. to skip the header line in your file, do this next(my_file)
The code below should help you through.
with open("data/food_and_nutrition.csv" 'r+', encoding='UTF8', newline='') as my_file:
writer = csv.writer(my_file)
csv_reader = csv.reader(my_file)
# Skip CSV heading
next(csv_reader)
for line in csv_reader:
if new_data not in line:
# To write
writer.writerow(new_data)