Actually i am trying to export a csv file with some data and below is my code
import csv
from cStringIO import StringIO
import web
def download(list__of_records):
csv_file = StringIO()
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Name', 'Link'])
for i in list_of_records :
csv_writer.writerow([i[0],i[1]])
web.header('Content-Type','text/csv')
web.header('Content-disposition', 'attachment; filename=%s.csv'%file_name)
return csv_file.getvalue()
list_of_records_1 = [('name',"fedrik"),('age','73'),('city','portland')]
list_of_records_2 = [('name',"wow"),('age','466'),('city','asdsa')]
download(list_of_records_1)
Actually i will use the above code in some web page that downloads a csv with the list_of_records
data.
In the above code i am using web which is nothing but web.py framework i ma using to instruct browser to download a csv ifle
suppose i called the function download(list_of_records_1)
, then a csv file is downloaded with data in it as below
Name fedrik
age 73
city portland
suppose i call the same function with download(list_of_records_2)
, the output saving in to the csv is as below
Name fedrik
age 73
city portland
Name wow
age 466
city asd
That is if the data already matching in csv then its overwriting and if new data is encountered then the csv file is creating with previous data as well as present list_of_records_2
data.
So in the above code after storing the results in the buffer string StringIO()
and saving in to csv file, we should truncate/delete the buffer string data, so that when we call the same function with other list of results the previous data will not be write in to csv file of the current one
Can anyone please let me know how to truncate the buffer string StringIO()
in the above code ?