Search code examples
pythoncsvrow

Python csv writer / rewrite /overwrite a row or delete all the rows and add a new one


I create and open a csv file and every 60 secs:

I open the csv -> csv = csv.writer(csvOpen, dialect='excel')

And write a new row into it -> csv.writerow([value1,value2,value3])

I do have headers in row 1, so I want to overwrite the 2nd row every time with the new values. Is that even possible to modify a csv? I thought about: The writerow syntax adds me a new row at every executing. Could I delete the row after I write it ? Or decide in which row I want to write my values?

I dont really want to delete the file every 60secs and create a new one. I am not sure if thats good for the SD card in the raspberry :)

Thanks!

I found several posts but I couldnt figure it out :( no blaming / lmgtfy links pls....


Solution

  • If you always just want two rows , you can open the file that you use to write csv data using the mode w , which would overwrite the file and then use writerows() instead of writerow() to write multiple rows, then as parameter to the writerows() function you can pass a list of lists, the first sublist being the headers, and the second being the actual row.

    Example -

    import csv
    csvOpen = open('filename','w')
    c = = csv.writer(csvOpen, dialect='excel')
    c.writerows([[header1,header2,heaer3],[value1,value2,value3]])
    

    Please note do not use csv as the variable name, as it will overwrite your import for csv .