Search code examples
pythonjsonexport-to-csv

How to update csv data in mutiple rows running this code mutliple times per day?


I am running this code multiple times per day. The data I generate is overwritten after every successful run. Here is the code:

with open('r3edata.csv','w') as fhandle:
    writer = csv.writer(fhandle)
    items = body.items()
    writer.writerow([key for key, value in items])
    writer.writerow([value for key, value in items])

This is the body dictionary:

body = {
    'dont-ask-for-email': 0,
    'action': 'submit_user_review',
    'post_id': 76196,
    'email': email_random(),
    'subscribe': 1,
    'previous_hosting_id': prev_hosting_comp_random(),
    'fb_token': '',
    'title': review_title_random(),
    'summary': summary_random(),
    'score_pricing': star_random(),
    'score_userfriendly': star_random(),
    'score_support': star_random(),
    'score_features': star_random(),
    'hosting_type': hosting_type_random(),
    'author': x,
    'social_link': z,
    'site': '',
    'screenshot[image][]': '',
    'screenshot[description][]': '',
    'user_data_process_agreement': 1,
    'user_email_popup': '',
    'subscribe_popup': 1,
    'email_asked': 1
}

The functions I have used return different data every time.

The output I get from saving is this:

CSV file I get

CSV File I want:

CSV file I want

The functions used in the body dict return different value every time. There will be 100 rows at the end of the day if this worked perfectly.

TL;DR → Cannot append csv data into the final csv file I get. I have no clue how does it work.


Solution

  • To append data to a file in Python, open it with "a+" mode (instead of the "w" you're currently using). This means that you'll append new data to the file every time you open and write to it.

    Explanation:

    • 'a' means append.
    • '+' means it'll create the file if it doesn't exist.