Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a file without saving it to disk in python?

Tags:

python

csv

django

I'm using Python 2.7 and Django 1.7.

I have a method in my admin interface that generates some kind of a csv file.

def generate_csv(args):
    ...
    #some code that generates a dictionary to be written as csv
    ....

    # this creates a directory and returns its filepath
    dirname = create_csv_dir('stock')

    csvpath = os.path.join(dirname, 'mycsv_file.csv')
    fieldnames = [#some field names]

    # this function creates the csv file in the directory shown by the csvpath
    newcsv(data, csvheader, csvpath, fieldnames)

    # this automatically starts a download from that directory
    return HttpResponseRedirect('/media/csv/stock/%s' % csvfile)

All in all I create a csv file, save it somewhere on the disk, and then pass its URL to the user for download.

I was thinking if all this can be done without writing to disc. I googled around a bit and maybe content disposition attachment might help me, but I got lost in documentation a bit.

Anyway if there's an easier way of doing this I'd love to know.

like image 287
Saša Kalaba Avatar asked Sep 17 '15 15:09

Saša Kalaba


People also ask

How do I create a non existing file in Python?

To create a file if not exist in Python, use the open() function. The open() is a built-in Python function that opens the file and returns it as a file object. The open() takes the file path and the mode as input and returns the file object as output.

How does Python store data to a file?

Use file. write() to save data to a Python file Call open(file, mode) with file as the Python file being saved to and mode as "w" to return a writable file object. With file as the result from the previous step, call file. write(data) with data as a string to save it to file .

Which mode of Python allows saving files?

Saving a Text File in Python Opening a new file in write mode will create a file and after closing the file, the files get saved automatically. However, we can also write some text to the file.


1 Answers

Thanks to @Ragora, you pointed me towards the right direction.

I rewrote the newcsv method:

from io import StringIO
import csv


def newcsv(data, csvheader, fieldnames):
    """
    Create a new csv file that represents generated data.
    """
    new_csvfile = StringIO.StringIO()
    wr = csv.writer(new_csvfile, quoting=csv.QUOTE_ALL)
    wr.writerow(csvheader)
    wr = csv.DictWriter(new_csvfile, fieldnames = fieldnames)

    for key in data.keys():
        wr.writerow(data[key])

    return new_csvfile

and in the admin:

csvfile = newcsv(data, csvheader, fieldnames)

response = HttpResponse(csvfile.getvalue(), content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=stock.csv'
return response
like image 96
Saša Kalaba Avatar answered Oct 03 '22 21:10

Saša Kalaba