Python: CSV from Array

(Last Updated On: )

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.

  1. import csv, io
Way 1 Write (In Memory):
  1. #Create the string buffer
  2. output = io.StringIO()
  3.  
  4. #Setup the csv writer to write the results to a string buffer
  5. wr = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
Way 2 Write (File):
  1. #Crate the file itself in write mode
  2. f = open('filename.csv', 'w')
  3.  
  4. #Setup the csv writer to write the results to a file.
  5. 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.

  1. 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):
  1. b = bytes(output.getvalue(), 'utf-u')
Way 2 Read (File):
  1. f.close()
  2. 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.

  1. buffer = BytesIO()
  2. buffer.write(b)
  3. #You must seek to beginning otherwise it won't send anything back.
  4. 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.

  1. return send_file(buffer, mimetype='application/octet-stream', as_attachment=True, attachment_filename='myFile.csv')