Skip to content
Advertisement

How do I create and write headers to a csv file if it doesn’t exist, but if it already exists then write data?

my first post here in stackoverflow and trying to dip my feet into python by writing a program that calls data from an API of an online game I play :)

I’ve written the below code to create a .csv file if it doesn’t exist, and then use a for loop to call an API twice (each with different match IDs). The response is in JSON, and the idea is that if the file is empty (i.e. newly created), it will execute the if statement to write headers in, and if it’s not empty (i.e. the headers have already been written in), then to write the values.

My code returns a .csv with the headers written twice – so for some reason within the for loop the file size doesn’t change even though the headers have been written. Is there something i’m missing here? Much appreciated!

JavaScript

Advertisement

Answer

It’s possible that the file buffers instead of writing immediately to disk because IO is an expensive operation. Either flush the file before checking its size, or set a flag in your loop and check that flag instead of checking the file size.

JavaScript
Advertisement