如何使用Python生成要下载的csv文件?

时间:2017-08-03 09:56:13

标签: python csv

我正在csv文件中的数据库中编写一些内容,需要使用Python下载它。我在下面解释我的代码。

def createfile(request):
    """ search the file by using the file path"""

    if request.method == 'POST':
        param = request.POST.get('param')
        report = Reactor.objects.all()
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment;filename=status.csv'
        writer = csv.writer(response)
        writer.writerow(['Name', 'Status', 'Date'])
        for rec report:
            if report.status == 1:
                status = 'Start'
            if report.status == 0:
                status = 'Stop'
            if report.status == 2:
                status = 'Suspend'
            writer.writerow([report.rname, status, report.date]) 

这里我从数据库中获取数据并在此处写入CSV文件我需要下载该文件。

1 个答案:

答案 0 :(得分:0)

使用库csvrequest

import csv
import requests

csv_url = 
'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'


with requests.Session() as s:
    download = s.get(csv_url)

    decoded_content = download.content.decode('utf-8')

    cr = csv.reader(decoded_content.splitlines(), delimiter=',')
    my_list = list(cr)
    for row in my_list:
       print(row)

它为我工作。