Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I read and awrite addtional data to existing data in a csv file

my csv rerights new data instead of appending to existing data. And also, how do I skip header when looping

my_file = open("data/food_and_nutrition.csv",'w', encoding='UTF8')
writer = csv.writer(my_file)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading