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

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

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 .

Extending Anand S Kumars 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.

  1. add an csvOpen.close() to close the file stream itself however, this is not the best practice.

  2. 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

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

Leave a Reply

Your email address will not be published. Required fields are marked *