Rafael Tamayo
Rafael Tamayo

Reputation: 402

How to create a CSV file in python that can be saved in memory?

I'm creating a CSV file in django that when you got to a url it downloads the CSV file, it works great the only thing is that I would like that when the the file is being written it's stored in memory and not in hard disk. How do you do this with the import csv

This is for django that uses list to create the csv

def data_feed_file(request):
    open_publications = self.get_publications(user_context)

    with open('facebook_feed.csv', 'wb') as csvfile:
        filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
        filewriter.writerow(['id', 'title','description'])
        for op_pub in open_publications:
            filewriter.writerow([op_pub.id, op_pub.name, str(op_pub.description)])

    with open('facebook_feed.csv', 'rb') as myfile:
        response = HttpResponse(myfile, content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=facebook_feed.csv'

    return response

Upvotes: 3

Views: 2157

Answers (1)

SafeDev
SafeDev

Reputation: 672

You can save the csv file in a pandas DataFrame. Like so:

import pandas as pd

df = pd.read_csv('url_to_csv')

Then the csv is read by the pandas library and you don't have to save it to a drive.

Upvotes: 2

Related Questions