Reputation: 35
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....
Upvotes: 1
Views: 16090
Reputation: 11
Extending Anand S Kumar's post
import csv
csvOpen = open('filename','w')
c = = csv.writer(csvOpen, dialect='excel')
c.writerows([[header1,header2,heaer3],[value1,value2,value3]])
Could and should have a few things here.
add an csvOpen.close() to close the file stream itself however, this is not the best practice.
In my opinion you should be using with open, if you do this the file itself will be closed automatically.
import csv
with open('filename','w') as csvOpen:
c = = csv.writer(csvOpen, dialect='excel')
c.writerows([[header1,header2,heaer3],[value1,value2,value3]])
or simply add csvOpen.close() to the in OG answer submitted by Anand. Hope I helped to some capacity cheers and happy keyboard slaying!
Extra Note:
Mode 'w' on a file truncates the file itself, if you are looking to append use mode 'ab' in my opinion this typically works the best. Generally even in 'write' mode I still use 'wb'
Upvotes: 0
Reputation: 90999
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
.
Upvotes: 0