0

I have a little dashboard at work which generates keys and amounts of certain calculation groups. The user can also choose to export to a CSV file.

However, it is breaking because one calculation group has keys which have commas in them. So I need to make it semicolon deliminated, and hopefully in a way that opens nicely.

This is my code currently:

from flask import Flask, render_template, request, make_response, Response  

if 'export' in request.form.getlist('export'):
        out = []
        for k,v in result.items():
            out.append(k + ';' + str(v)  + '\n')
        csv = ''.join(out)
        response = make_response(csv)
        cd = 'attachment; filename = LCRdrillback.csv'
        response.headers['Content-Disposition'] = cd
        response.mimetime='text/csv' 
        return response 

The semi colon in that code block used to be a comma. How do I need to tweak this to make it semicolon friendly? So that opens with the keys and values in different columns?

I am using flask as well.

ifthenifthen
  • 265
  • 2
  • 11

2 Answers2

2

You can use the python module csv in order to read csv files easily. You are able to set the delimiter easily.

Reading example:

import csv
delimiter_type=';'

with open('file_name.csv', 'rb') as csv_file:
    spamreader = csv.reader(csv_file, delimiter=delimiter_type, quotechar='|')

Writing example:

import csv
delimiter_type=';'
with open('file_name.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=delimiter_type,
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Idan
  • 333
  • 2
  • 8
  • I'm very n00by - can you show me how you would modify the code that I showed you? I didn't write it, but I'm in charge of it now. I have tried a few things but they didn't work. – ifthenifthen Sep 21 '17 at 18:46
1

As I understand, the problem is how the file opens in a spreadsheet application. I think all applications running on Windows use double quotes as text delimiter by default (MS Excel and LibreOffice for sure) and this way you can escape the field and stick to the classic comma delimiter for your file. Example: "subfield1, subfield2", field2, field3. On Unix, I have not tried, but I believe Unix-style escaping would work: subfield1\,subfield2, field2. I don't think a spreadsheet application would open nicely a csv file that is not delimited with a comma without passing through a "Text import" process.

CynicalSection
  • 694
  • 4
  • 8