In this tutorial I will explain how to turn an array to a csv file. I will show you two ways. One is in memory and the other is to a file.
For both ways you need to import csv and io package.
import csv, io
Way 1 Write (In Memory):
#Create the string buffer output = io.StringIO() #Setup the csv writer to write the results to a string buffer wr = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
Way 2 Write (File):
#Crate the file itself in write mode f = open('filename.csv', 'w') #Setup the csv writer to write the results to a file. wr = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
Technically both ways have the same setup for the csv writer. Then to write results to the csv writer you then pass an array of values like below.
wr.writerow(['123',5,4,'value'])
To Read the contents of the file or string buffer depends on which way you chose. I show you those ways below.
Way 1 Read (In Memory):
b = bytes(output.getvalue(), 'utf-u')
Way 2 Read (File):
f.close() file_data = open('filename.csv', 'r').read()
If you want to send the file down using something like flask send_file then you need to convert it to BytesIO.
buffer = BytesIO() buffer.write(b) #You must seek to beginning otherwise it won't send anything back. buffer.seek(0)
Now if you are sending it as a file back to the user and are using something like flask this is how you do that. Pretty straight forward.
return send_file(buffer, mimetype='application/octet-stream', as_attachment=True, attachment_filename='myFile.csv')
You must be logged in to post a comment.