-1

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)
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34

1 Answers1

0

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)
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34